node.js - res.send和res.json有什么区别?
大家讲道理
大家讲道理 2017-04-17 16:30:36
[Node.js讨论组]

除了res.json里面的值必须是json外,还有什么区别呢?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(1)
伊谢尔伦

Difference between res.send and res.json in Express.js 搬运一个stackoverflow上的答案

下面是翻译过来的高票答案:

当传递对象或数组时,这两个方法是相同的,但是res.json()也会转换非对象,如nullundefined,这些无效的JSON。

该方法还使用json replaceacerjson spaces的设置,因此您可以使用更多选项格式化JSON。 例如:

app.set('json spaces', 2);
app.set('json replacer', replacer);

传递给JSON.stringify()类似:

JSON.stringify(value, replacer, spacing);
// value: 需要格式化的对象
// replacer: stringify 时如何转化属性的规则
// spacing: 锁紧的空格数量

res.json方法的中res.send部分没有的代码:

var app = this.app;
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = JSON.stringify(obj, replacer, spaces);

最终它使用res.send发送请求

this.charset = this.charset || 'utf-8';
this.get('Content-Type') || this.set('Content-Type', 'application/json');

return this.send(body);
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号