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

brg*_*brg 189 javascript http node.js express

两者之间的实际区别是什么res.send,res.json因为两者似乎都执行响应客户端的相同操作.

hex*_*ide 199

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

该方法还使用json replacerjson spaces应用程序设置,因此您可以使用更多选项格式化JSON.这些选项设置如下:

app.set('json spaces', 2);
app.set('json replacer', replacer);
Run Code Online (Sandbox Code Playgroud)

并传递给了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
Run Code Online (Sandbox Code Playgroud)

这是res.json()send方法没有的方法中的代码:

var app = this.app;
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = JSON.stringify(obj, replacer, spaces);
Run Code Online (Sandbox Code Playgroud)

该方法最终res.send()结束:

this.charset = this.charset || 'utf-8';
this.get('Content-Type') || this.set('Content-Type', 'application/json');

return this.send(body);
Run Code Online (Sandbox Code Playgroud)


Pet*_*ons 64

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

res.json最终打电话res.send,但在此之前:

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


tec*_*oke 13

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