user1547174 user1547174 - 5 months ago 26x
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'


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

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



type: "POST",
data: data,
success: function(data, 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!


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

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