NodeJs Express - 如何返回HTTP错误代码(400,401,500)以及JSON OBJECT

Luc*_*tos 3 node.js express

我有一个使用express和NodeJs的web api.这听起来很基本,但我找不到解决方案.如何使用http状态代码和Json对象返回响应?

例如:

res.send(500,{success:false,错误'抱歉,错误'});

即使我返回一个错误的http响应代码,我想返回一个json对象.我试图使用一些请求方法,但没有人给出设置http状态代码和json对象的选项.

我很确定我可能会遗漏一些东西,因为这对于web api框架来说是非常基本的.

提前致谢.

Man*_*umi 12

根据 Express(版本 4+)文档,您可以使用:

res.status(400);
res.send('Response');
Run Code Online (Sandbox Code Playgroud)

您可以像这样在回复中添加状态代码

res.status(500).json({success: false, error 'Sorry, error'});
Run Code Online (Sandbox Code Playgroud)


Shu*_*ubh 5

你可以这样做

res.json({ user: 'tobi' })//sends a json only
res.status(500).json({ error: 'message' })//sends json with status code
Run Code Online (Sandbox Code Playgroud)