user1547174 user1547174 - 6 months ago 46
Ajax Question

How to send custom error message to user in node.js + ajax

Can someone help me with sending an error message from the server to client side via ajax? For example, if my server side returns a 404 error, I want it to also send a custom message: 'something is wrong'

server.js

api.get('/api/some_route', function(req, res, next) {

res.sendStatus(404, 'something is wrong');

});


client.js

$.ajax({
type: "POST",
data: data,
success: function(data, status) {
console.log(status);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus) //returns error
console.log(errorThrown) //returns bad request
//I want to someohow print the 'something is wrong' message from the api
}
});


Thanks in advance!

Answer

You just have to call the status method before calling send or json:

res.status(404).send({ error: "Something is wrong"});