最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin6浏览0评论

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 badges
Add a comment  | 

3 Answers 3

Reset to default 15

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'});

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论