参考:https://cloud.tencent.com/developer/ask/32482
个人更加建议使用res.json发送数据
查看了一下官方的源代码,发行res.json是先把对象序列化成了字符串类型然后在通过res.send发送出去,所以在数据处理中,res.json相对更全面!
比如浮点数的发送对比区别
res.json(223423.1232424234) //正确
res.send(223423.1232424234) // 抛出异常
当传递对象或数组时,这些方法是相同的,但是res.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
这是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);
该方法最终成为res.send()
最后:
this.charset = this.charset || 'utf-8';
this.get('Content-Type') || this.set('Content-Type', 'application/json');
return this.send(body);