Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJs Express - How to return HTTP ERROR CODE (400,401,500) plus JSON OBJECT

I have a web api which is using express and NodeJs. This sounds really basic but I could not found a solution. How can I return a response with http status code and Json object?

For example:

res.send(500, {success: false, error 'Sorry, error'});

Even if I return an error http response code, I would like to return a json object. I am trying to use some request methods, but no one of them give the option to set http status code and json object.

I am pretty sure that I might be missing something, because this is really basic for a web api framework.

Thanks in advance.

like image 402
Lucas Santos Avatar asked Feb 10 '19 08:02

Lucas Santos


Video Answer


2 Answers

As per the Express (Version 4+) docs, you can use:

res.status(400);
res.send('Response');

You can add a status code with your response like this

res.status(500).json({success: false, error 'Sorry, error'});
like image 74
Manzurul Hoque Rumi Avatar answered Oct 20 '22 17:10

Manzurul Hoque Rumi


You could do something like this

res.json({ user: 'tobi' })//sends a json only
res.status(500).json({ error: 'message' })//sends json with status code
like image 42
Shubh Avatar answered Oct 20 '22 19:10

Shubh