gpt4 book ai didi

node.js - res.send 和 res.json 的区别

转载 作者:搜寻专家 更新时间:2023-10-31 22:18:05 25 4
gpt4 key购买 nike

有什么区别

res.status(STATUS_CODE).send({"message" : "this is the message" });

res.status(STATUS_CODE).json({"message" : "this is the message" });

虽然检查了the similar question但这是在 express 3 的上下文中,我正在寻找 express 4

最佳答案

最终,两者将实现相同的目标。如果你用一个对象调用 res.send,它会在 res.send 中点击这个开关:

switch (typeof chunk) {
// string defaulting to html
case 'string':
if (!this.get('Content-Type')) {
this.type('html');
}
break;
case 'boolean':
case 'number':
case 'object':
if (chunk === null) {
chunk = '';
} else if (Buffer.isBuffer(chunk)) {
if (!this.get('Content-Type')) {
this.type('bin');
}
} else {
return this.json(chunk);
}
break;
}

如果您发送的对象不是缓冲区 - 它将调用 res.json

res.json 只是将 Content-Type header 设置为 application/json 并通过 JSON.stringify< 运行对象 - 具有指定的替换函数和间隔值。最终它调用 res.send

res.send 的调用发送了一个字符串,case 语句将中断,导致函数的其余部分运行。发送函数的其余部分设置诸如 etag、内容大小等内容。您可以通过查看 express code 了解更多信息。 .

当您向它们发送非对象响应(例如字符串、数字等)时,它们开始有所不同。在这种情况下,res.json 将通过 JSON.stringify 运行它> 但 res.send 不会:导致不同的 Content-Type header 和内容。

编辑:回答您对其他答案的评论,发送不同的状态代码仍然会表现相同。

关于node.js - res.send 和 res.json 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37698782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com