res.send和res.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);
参见:res.json源代码上的expressjs。
Res.json最终调用res.send,但在此之前:
尊重json空间和json替换应用程序设置 确保响应将有utf-8字符集和application/json内容类型
查看发送的报头…
Res.send使用content-type:text/html
Res.json使用content-type:application/json
Edit: send实际上根据给定的内容更改发送的内容,因此字符串以text/html的形式发送,但如果传递给它一个对象,它会发出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。
推荐文章
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 什么是HTTP“主机”报头?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- CALL_AND_RETRY_LAST分配失败-进程内存不足
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 在Ubuntu上安装Node.js
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?