res.send和res.json之间的实际区别是什么,因为两者似乎都执行相同的响应客户端操作。
当前回答
参见:res.json源代码上的expressjs。
Res.json最终调用res.send,但在此之前:
尊重json空间和json替换应用程序设置 确保响应将有utf-8字符集和application/json内容类型
其他回答
res.json强制参数为JSON。Res.send将接受一个非json对象或非json数组并发送另一种类型。例如:
这将返回一个JSON数字。
res.json(100)
这将返回一个状态代码,并发出使用sendStatus的警告。
res.send(100)
如果你的参数不是JSON对象或数组(null, undefined, boolean, string),并且你想确保它以JSON形式发送,请使用res.json。
查看发送的报头…
Res.send使用content-type:text/html
Res.json使用content-type:application/json
Edit: send实际上根据给定的内容更改发送的内容,因此字符串以text/html的形式发送,但如果传递给它一个对象,它会发出application/json。
参见:res.json源代码上的expressjs。
Res.json最终调用res.send,但在此之前:
尊重json空间和json替换应用程序设置 确保响应将有utf-8字符集和application/json内容类型
当传递对象或数组时,方法是相同的,但res.json()也会转换非对象,如null和undefined,这不是有效的JSON。
该方法还使用json replace和json spaces应用程序设置,因此您可以使用更多选项格式化json。这些选项的设置如下:
app.set('json spaces', 2);
app.set('json replacer', replacer);
并传递给JSON.stringify(),如下所示:
JSON.stringify(value, replacer, spacing);
// value: object to format
// replacer: rules for transforming properties encountered during stringifying
// spacing: the number of spaces for indentation
这是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);
推荐文章
- 在数组中获取所有选中的复选框
- HTTP POST返回错误:417“期望失败。”
- 如何为Firebase构建云函数,以便从多个文件部署多个函数?
- 如何发送推送通知到web浏览器?
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- 有没有办法修复包锁。json lockfileVersion所以npm使用特定的格式?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;