node.js Express 4.14 - 如何使用自定义消息发送 200 状态?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38158027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:22:15  来源:igfitidea点击:

Express 4.14 - How to send 200 status with a custom message?

node.jsexpresshttpresponse

提问by laukok

How can I send status and message in express 4.14?

如何在 express 4.14 中发送状态和消息?

For: res.sendStatus(200);

对于: res.sendStatus(200);

I get OK on my browser but I want it to display a custom message such as: Success 1

我在浏览器上正常运行,但我希望它显示一条自定义消息,例如: 成功 1

res.sendStatus(200);
res.send('Success 1');

Error:

错误:

Error: Can't set headers after they are sent.

错误:发送后无法设置标头。

If I do this:

如果我做这个

res.status(200).send(1);

Error:

错误:

express deprecated res.send(status): Use res.sendStatus(status) instead

表示不推荐使用的 res.send(status):使用 res.sendStatus(status) 代替

Any ideas?

有任何想法吗?

回答by Dima Grossman

You can use:

您可以使用:

res.status(200).send('some text');

if you want to pass number to the send method, convert it to string first to avoid deprecation error message.

如果要将 number 传递给 send 方法,请先将其转换为字符串以避免弃用错误消息。

the deprecation is for sending status directly inside send.

弃用是直接在发送内部发送状态。

res.send(200) // <- is deprecated

BTW- the default status is 200, so you can simply use res.send('Success 1'). Use .status() only for other status codes

顺便说一句- 默认状态是 200,所以你可以简单地使用 res.send('Success 1')。.status() 仅用于其他状态代码

回答by robertklep

You shouldn't be getting that last error if you're using that exact code:

如果您使用的是那个确切的代码,您不应该得到最后一个错误:

res.status(200).send('Success 1')

My guess is that you're not using the string "Success 1"but a numerical variable or value instead:

我的猜测是您没有使用字符串“Success 1”,而是使用数字变量或值:

let value = 123;
res.status(200).send(value);

That wouldtrigger the warning. Instead, make sure that valueis stringified:

触发警告。相反,请确保value字符串化:

let value = 123;
res.status(200).send(String(value));