Express.js中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
这是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应用程序设置 - 确保响应将有utf8字符集和application / json内容types
寻找标题发送…
res.send使用content-type:text / html
res.json使用内容types:application / json