res.send
和res.json
之间的实际区别是什么?它们似乎执行相同的响应客户端操作。
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.send()
方法中没有的 res.json()
方法的代码:
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
最终会调用res.send
,但在此之前:
json spaces
和json replacer
utf-8
字符集和application/json
内容类型查看发送的头信息...
res.send
方法使用 content-type:text/html
res.json
方法使用 content-type:application/json
编辑:实际上,send
方法会根据传入的内容进行更改发送的格式。如果传入的是字符串,则会使用text/html
格式发送;但如果传递一个对象,则会使用application/json
格式。
res.json
将参数强制转换为JSON格式。res.send
将接受非JSON对象或非JSON数组并发送其他类型的数据。例如:
这将返回一个JSON数字。
res.json(100)
sendStatus
。res.send(100)
null
,undefined
,boolean
,string
),并且你想确保它以JSON格式发送,可以使用res.json
。非JSON对象
或者数组
。所以请尽可能让它更清晰明了。 - yaya