res.send和res.json有什么区别?

除了res.json里面的值必须是json外,还有什么区别呢?

阅读 7.8k
1 个回答

Difference between res.send and res.json in Express.js 搬运一个stackoverflow上的答案

下面是翻译过来的高票答案:

当传递对象或数组时,这两个方法是相同的,但是res.json()也会转换非对象,如nullundefined,这些无效的JSON。

该方法还使用json replaceacerjson spaces的设置,因此您可以使用更多选项格式化JSON。 例如:

app.set('json spaces', 2);
app.set('json replacer', replacer);

传递给JSON.stringify()类似:

JSON.stringify(value, replacer, spacing);
// value: 需要格式化的对象
// replacer: stringify 时如何转化属性的规则
// spacing: 锁紧的空格数量

res.json方法的中res.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);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题