1

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!

1 Answer 1

1

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

res.status(404).send({ error: "Something is wrong"});
Sign up to request clarification or add additional context in comments.

1 Comment

I tried this. Still it is goes in ajax success. How can I throw it in ajax error?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.