node.js Express.js 中 res.send 和 res.json 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19041837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:45:51  来源:igfitidea点击:

Difference between res.send and res.json in Express.js

javascriptnode.jshttpexpress

提问by brg

What is actual difference between res.sendand res.jsonas both seems to perform same operation of responding to client.

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

回答by hexacyanide

The methods are identical when an object or array is passed, but res.json()will also convert non-objects, such as nulland undefined, which are not valid JSON.

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

The method also uses the json replacerand json spacesapplication settings, so you can format JSON with more options. Those options are set like so:

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

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

And passed to a JSON.stringify()like so:

并传递给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

This is the code in the res.json()method that the send method doesn't have:

这是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);

The method ends up as a res.send()in the end:

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

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

return this.send(body);

回答by Peter Lyons

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

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

res.jsoneventually calls res.send, but before that it:

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

  • respects the json spacesand json replacerapp settings
  • ensures the response will have utf8 charset and application/json content-type
  • 尊重json spacesjson replacer应用程序设置
  • 确保响应将具有 utf8 字符集和 application/json 内容类型

回答by technicalbloke

Looking in the headers sent...
res.send uses content-type:text/html
res.json uses content-type:application/json

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