Axios delete giving 404 after deleting from database - node.js

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.

Related

ReferenceError: auth is not defined nodejs

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.

Cannot extract error message from error.message

I have this line of code in my express app:
catch (err) {
res.status(500).send(err.message);
}
when i console log the error I get this message:
name: 'TokenExpiredError',
message: 'jwt expired',
but when I recieve the error in my client using axios request like so:
catch (err) {
console.log(err.message)
I get this : Request failed with status code 500
how can I access the original massage?
You don't want to simply catch the error, a 500 error is just a 500 error (with it's own generic message).
You need to extract the message you send in the response from the response body. This is from the github issues pages for axios https://github.com/axios/axios/issues/960:
axios
.post('ajax/register/otp', this.registerData)
.then(function (response) {
...
})
.catch(function (error) {
console.log(error.response);
});

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});

NodeJs not running in the port 4000

I am trying to call an api using axios in react.I am using express and node js .when api is called using axios.get() .it returns error after some time.when i run node in port 4000(localhost:4000/data) its not loading.
//api
router.route('/issue').get((req, result) => {
Issue.find((err, issue) => {
if (err)
console.log(err);
else
result.json(issue);
});
});
//api call in react file
axios.get('http://localhost:4000/issue').then(res=>{
console.log('success');
}).catch(err=>{
console.log('error');
});
You need to handle the error in your api. If you just console.log, your frontend is still waiting for a response
And if your back don't sent any response, your browser cancel the request with a timeout, that is the error you got
//api
router.route('/issue').get((req, result) => {
Issue.find((err, issue) => {
if (err)
result.status(404).json({
success: false,
msg: "There has been a problem in your request"
});
else
result.json(issue);
});
});

Error: Can't set headers after they are sent. - NodeJS and Express

I have a NodeJS Rest API where I have a user collection, besides that I do user SMS verification.
This is the controller for the POST /:id/verification
exports.verification = (req, res) => {
const id = req.params.id
return User.find(id)
.then( user => {
if (user.code !== req.body.code) {
res.json({ message: 'Incorrect code' })
res.sendStatus(500)
return
}
user.isVerified = true
user.save( error => {
if (error) {
res.json({ message: 'Failed to update user' })
res.sendStatus(500)
return
}
res.json({ user })
res.sendStatus(200)
} )
} )
.catch( error => {
res.json({ error })
} )
}
But the thing is that when I post to /:id/verification I get this error
Error: Can't set headers after they are sent. - NodeJS and Express
On this line:
res.json({ user })
res.sendStatus(200)
But I dont understand why, I dont send any response before this.
Can someone explain me what Im doing wrong?
you are using both res.json() and res.sendStatus() both together, both of them send response back, That is why it is showing error that Can't set headers after they are sent.
you should use only one of them.
If you want to send status along with the JSON response, you can try this:
res.status(500).json({ message: 'Incorrect code' });
Also, status of 200 is default when using res.send, res.json, etc. So you dont need to send status 200 with res.json()
res.json() send object to the clilent and after that you are trying to set the header with status code. So, it shows the error message. Use following code for set status and sending the content in the same time.
res.status(500).json({ error: 'message' } /* json object*/);

Resources