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

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

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

对于: res.sendStatus(200);

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

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

错误:

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

如果我这样做 this:

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

错误:

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

有什么想法吗?

您可以使用:

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

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

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

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

BTW - 默认状态为 200,因此您可以简单地使用 res.send('Success 1')。 仅对其他状态代码使用 .status()

如果您使用的是确切的代码,则不应出现最后一个错误:

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

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

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

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

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