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.
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.
Share Improve this question edited Jun 10, 2020 at 20:12 Shubham Dixit 1 asked Feb 10, 2019 at 8:34 Lucas SantosLucas Santos 3,2515 gold badges21 silver badges31 bronze badges3 Answers
Reset to default 15As 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'});
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
I also had the same issue but I finally solved it with something very simple
res.status(400).json({error:"error message here"})
This worked although at the Network on chrome 200 appeared