两者之间的实际区别是什么?res.send
和res.json
两者似乎对都客户端执行相同的响应操作。
res.json
最终响应res.send
,但在此之前:
json spaces
和json replacer
应用程序设置当传递对象或数组时,这些方法是相同的,但是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()
方法,而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);