Express.js中res.send和res.json之间的区别

时间:2013-09-27 02:38:16

标签: javascript node.js http express

res.sendres.json之间的实际差异是什么,因为两者似乎都执行了响应客户端的相同操作。

4 个答案:

答案 0 :(得分:195)

传递对象或数组时方法相同,但res.json()也会转换非{J}的非nullundefined等非对象。

该方法还使用json replacerjson 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);

答案 1 :(得分:60)

https://github.com/visionmedia/express/blob/ee228f7aea6448cf85cc052697f8d831dce785d5/lib/response.js#L174

res.json最终会调用res.send,但在此之前:

  • 尊重json spacesjson replacer应用设置
  • 确保响应将具有utf8字符集和application / json内容类型

答案 2 :(得分:12)

查看发送的标题...
res.send使用content-type:text / html
res.json使用content-type:application / json

答案 3 :(得分:1)

res.json将参数强制为JSON。 res.send将采用非json对象或非json数组,并发送另一种类型。例如:

这将返回一个JSON数字。

res.json(100)

这将返回状态码并发出警告以使用sendStatus。

res.send(100)

如果您的参数不是JSON对象或数组(空,未定义,布尔值,字符串),并且要确保将其作为JSON发送,请使用res.json

相关问题