Express.js 中 res.send 和 res.json 之间的区别
Difference between res.send and res.json in Express.js
res.send
和res.json
之间的实际区别是什么,因为两者似乎执行相同的响应客户端的操作。
当传递对象或数组时,这些方法是相同的,但res.json()
也会转换非对象,例如 null
和 undefined
,这些不是有效的 JSON。
该方法还使用json replacer
和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);
参见:在 expressjs 上res.json
源代码。
res.json
最终调用res.send
,但在此之前它:
- 遵守
json spaces
和json replacer
应用设置 - 确保响应具有
utf-8
字符集和application/json
内容类型
查看发送的标头...
res.send
使用content-type:text/html
res.json
使用content-type:application/json
编辑:发送实际上会根据给定的内容更改发送的内容,因此字符串作为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
。
- 函数参数中的数据与指定变量之间的任何性能差异
- 全局变量和全局对象的属性之间有什么区别吗
- java.net和javascript之间正则表达式的差异
- JavaScript中的函数和对象之间没有区别吗?
- 获取@ResponseBody的一部分作为主干和Spring MVC控制器之间的参数
- Jquery在函数之间传递表行
- 根据某些条件在视图之间切换
- 在控制器和数据对象之间同步数据
- d3中堆栈函数和嵌套函数之间的差异
- JQuery:在页面之间滑动
- 如何使用JavaScript查找1和N之间的所有数字的总和
- 操作放置在画布上的元素之间的连接
- 在下划线中使用_(obj).map(callback)和_.map(obj,callback)之间的区别
- jquery在表单之间切换
- Nodejs API控制器,用于在API之间切换
- 如何在aspx页面之间传递参数
- 在索引.html和应用.js [node.js] 之间共享变量
- 什么是&&在没有if的行中的变量之间
- DOM元素和angular元素之间的主要区别是什么
- Express.js 中 res.send 和 res.json 之间的区别