res.send
和 res.json
之间的实际区别是什么,因为两者似乎都执行相同的响应客户端操作。
最佳答案
传递对象或数组时方法相同,但res.json()
也会转换非对象,如null
和undefined
,它们不是有效的 JSON。
该方法还使用 json replacer
和 json 空格
应用程序设置,因此您可以使用更多选项格式化 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);
关于javascript - Express.js 中 res.send 和 res.json 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19041837/