The methods are identical when an object or array is passed, but res.json()
will also convert non-objects, such as null
and undefined
, which are not valid JSON.(传递对象或数组时,方法是相同的,但res.json()
也将转换非对象,例如null
和undefined
,这些对象是无效的JSON。)
The method also uses the json replacer
and json spaces
application settings, so you can format JSON with more options.(该方法还使用json replacer
和json spaces
应用程序设置,因此您可以使用更多选项格式化JSON。) Those options are set like so:(这些选项设置如下:)
app.set('json spaces', 2);
app.set('json replacer', replacer);
And passed to a JSON.stringify()
like so:(并传递给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
This is the code in the res.json()
method that the send method doesn't have:(这是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);
The method ends up as a res.send()
in the end:(该方法最终以res.send()
结尾:)
this.charset = this.charset || 'utf-8';
this.get('Content-Type') || this.set('Content-Type', 'application/json');
return this.send(body);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…