node.js - res.send和res.json有什么区别?
大家讲道理
大家讲道理 2017-04-17 16:30:36
0
1
601

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

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(1)
伊谢尔伦

Difference between res.send and res.json in Express.js Moving an answer on stackoverflow

The following is the translated answer with high votes:

When passing objects or arrays, these two methods are the same, but res.json() will also convert non-objects, such as null and undefined, these are invalid JSON. 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 method also uses the settings of json replaceacer and json spaces so you can format JSON with more options. For example: 🎜
this.charset = this.charset || 'utf-8';
this.get('Content-Type') || this.set('Content-Type', 'application/json');

return this.send(body);
🎜 Passed to JSON.stringify() is similar to: 🎜 rrreee 🎜 Code that is not included in the res.send part of the res.json method: 🎜 rrreee 🎜Finally it uses res.send to send the request🎜 rrreee
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template