ReferenceError: auth is not defined nodejs - node.js

I've created a puppy database using My SQL workbench, I am not developing multiples routers that allow me to view all puppies, add a puppy, update a puppy etc. I am currently working on the router to delete a puppy. However, I keep getting a 'ReferenceError: auth is not defined' error.
Here is my code for the router.delete:
try {
const puppyID = req.params.id;
const token = await auth.verify('puppy.remove', req);
await puppyCtrl.removePuppy(puppyID, token.id);
res.json({ message: 'Puppy Removed Successfully' });
} catch (err) {
console.log(err);
res.json({ message: "Failed to delete puppy" });
}
});
I am testing it on Postman and get the "Failed to delete puppy" error on postman. So it does get to the catch. However, I think there is probably an error within my try statement.

Related

EXPRESS - Some API endpoints are not found despite valid request

I have a simple Reddit clone project written in express. I noticed that some endpoints are throwing errors despite having a correct URL. Here is my code.
App.js
app.use("/api", router);
Router
router.route("/register")
.post(UsersController.APIregisterUser);
router.route("/login")
.post(UsersController.APIlogin);
router.route("/posts/") // Fetch all posts
.get(PostsController.APIgetPosts)
.post(Utility.verifyToken, PostsController.APIaddPost);
router.route("/comment/submit/:id/") // /posts/comment/123456789
.put(Utility.verifyAndPassData, PostsController.APIaddComment);
router.route("/posts/vote")
.put(Utility.verifyAndPassData, PostsController.APIcastVote);
router.route("/posts/:id/") // req.params.id
.get(PostsController.APIgetPostByID)
.delete(Utility.verifyToken, PostsController.APIdeletePost);
router.route("/posts/categories")
.get(PostsController.APIgetCategories);
When I try to fetch all posts by going to http://localhost:8080/api/posts (GET) via Insomnia, it works as intended. However, when I try to post a comment by going to http://localhost:8080/api/comment/submit/*post's id* (PUT) , it says 404 not found. I checked the PostsController.APIaddComment if the error is in there but there seems to be no error on that part. I even tried replacing the whole function with a console.log("test") to see if the endpoint is being reached but none happens.
Here is the PostsController.APIaddComment:
static async APIaddComment(userData, req, res, next) {
try {
const commentBody = {
user: req.body.username,
body: req.body.body,
date: new Date()
}
const addComment = await PostsDAO.addComment(commentBody, req.params.id);
res.status(200).json({
status: "Comment submitted!",
addComment
});
} catch(e) {
res.status(400).json({
error: `Error in PostsController APIaddComment: ${e}`
})
}
}
Other than that particular function, everything works as intended. What could be the possible cause?

Why am I getting a "400: Bad Request" but the request successfully posts to my DB

I am not sure what is happening. I had all the same code setup in dev using localhost and everything was working fine. I hosted my app to Vercel and my API to heroku and from what I can tell the API is working perfectly. The issue now is when I make a post request I get a 400 Bad Request error in the browser but it still makes the request and posts to my DB I have setup. Any help can be appreciated. I built this application in a MERN stack with NEXT.js
Here is my client side Post request
const postSubmit = async e => {
e.preventDefault();
try {
const { data } = await axios.post('/create-post', { content, image });
if(data.error) {
toast.error(data.error);
} else {
setPage(1);
newsFeed();
toast.success("Post created");
setContent('');
setImage({});
// socket.emit('new-post', data);
}
} catch(e) {
console.log(e);
}
}
Here is my server side handling of the post request
export const createPost = async (req, res) => {
const { content, image } = req.body;
if(!content.length) {
return res.json({
error: 'Content is required'
})
}
try {
const post = new Post({ content, image, postedBy: req.user._id });
await post.save();
const postWithUser = await Post.findById(post._id).populate('postedBy', '-password -secret');
res.json(postWithUser);
} catch (e) {
console.log(e);
res.sendStatus(400);
}
};
And here is what the browser is telling me
Chrome Browser Info
This is most likely caused by a typo on the MongoDB connection string (URI), similar to this answer.
In the linked answer, the typo was the semi-colon in &w=majority;. In your case, the value is somehow majorityDATABASE=, so double-check your MongoDB connection string and try to remove the extra DATABASE= in the write concern parameter.
It's likely that the await Post.findById() call is not finding a result which could be throwing an error when you try to call res.json(postWihUser). That would then cause an error when postWithUser is not defined.
What is logged to the server's terminal when an error occurs? That should help you identify the problem.

Axios delete giving 404 after deleting from database

I am sending a delete request using axios from my React frontend to node js express backend with mongo DB. Although the data does get deleted from my database but I still get an error 404 Not Found.
Here is React code
axios
.delete(`http://localhost:8000/notes/${id}`)
.then(res => {
console.log("The response is "+res.data)
})
.catch(err => {
console.log("There was an error "+ JSON.stringify(err.response))
});
Here is node js express code app.js
app.delete("/notes/:notesId", cors(), function(req, res) {
const query={_id:req.params.notesId};
console.log("The notes id is "+ query);
Note.findOneAndDelete(query, function(err) {
if(!err) {
console.log("The item got successfully deleted");
res.redirect("/");
} else {
console.log(err)
}
})
})
Please note that the entry gets deleted from my database but i get this error in my browser console :
xhr.js:178 DELETE http://localhost:8000/ 404 (Not Found)
App.jsx:26 There was an error {"data":"<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot DELETE /</pre>\n</body>\n</html>\n","status":404,"statusText":"Not Found","headers":{"content-length":"142","content-type":"text/html; charset=utf-8"},"config":{"url":"http://localhost:8000/notes/5ee130b65dc5f521acf60f38","method":"delete","headers":{"Accept":"application/json, text/plain, */*"},"transformRequest":[null],"transformResponse":[null],"timeout":0,"xsrfCookieName":"XSRF-TOKEN","xsrfHeaderName":"X-XSRF-TOKEN","maxContentLength":-1},"request":{}}
I am trying to hit the complete url till notes id but it is only considering till root
Try modifying the res to send a 200 OK status if the object gets deleted. You could also send a message for your frontend to display in this manner
if(!err) {
res.status(200).json({ message: 'The item got successfully deleted', error: false });
} else {
res.status(500).json({message : 'Oops and error occurred', error : true});
Regardless a simple res.status(200).end(); should suffice as well for your situation.

Noob - API getting stuck in a simple GET (express,node)

In trying to build my first express API, I am encountering many problems. I am following some simple guide on youtube, and his code works (FOR HIM). When I try it with Postman, I simply get nothing, but it appears to be in some kind of loop (because I handle the errors)
I have checked that my route is ok, and tried experimenting with next() (which seems like I don't need it just yet)
Player is my model made with Mongoose
app.get("/players/:id", (req, res) => {
const id = req.params.id;
Player.findById(id)
.exec()
.then(doc => {
console.log("From database", doc);
if (doc) {
res.status(200).json(doc);
} else {
res
.status(404)
.json({ message: "No valid entry found for provided ID" });
}
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
});
So when trying a GET in Postman on:
http://localhost:3000/players/5cf66338f00c424494316eb2
I get a loading screen, and after some time "There was an error connecting to...".
Any help/tips/solution/insights are appreciated!
If your repo is up-to-date, then you are not connecting your app with your database.
Add the following code in your app replacing the database with your own database:
mongoose.connect('mongodb://localhost:27017/database', {useNewUrlParser: true});

Delete request on node.js REST API works fine from postman not from app

I have a rest API and an app that uses it. The app and postman can both make get requests perfectly. The problem is that on delete requests the app does not work Most of the time but postman works every time. The app also always receives an OK if it works or not. Any help would be appreciated. I am using Node.js and MongoDB for the api and Xamarin for the app
Delete code on server:
// Delete a fish with the specified fishId in the request
exports.delete = (req, res) => {
console.log("Atempting to delete fish with id: " + req.params.fishId)
Fish.findByIdAndRemove(req.params.fishId)
.then(fish => {
if (!fish) {
return res.status(404).send({
message: "Fish not found with id " + req.params.fishId
});
}
if (!Fish.findByID(req.params.fishId)) {
return res.status(200).send({
message: "Fish deleted sucsessfully"
});
}
return res.status(500).send({
message: "Could not delete fish with id " + req.params.fishId
});
}).catch(err => {
if (err.kind === 'ObjectId' || err.name === 'NotFound') {
return res.status(404).send({
message: "Fish not found with id " + req.params.fishId
});
}
return res.status(500).send({
message: "Could not delete fish with id " + req.params.fishId
});
});
};
Just wondering why is this with no callback/.then?
if (!Fish.findByID(req.params.fishId)) {
return res.status(200).send({
message: "Fish deleted sucsessfully"
});
}
Isn't findByID async just like findOneAndRemove?
findByID is async yes, you should handle it that way, or maybe a solution could be to check with ObjectID.isValid() before? Then check for the resolved document would be just enough.

Resources