res.send
和res.json
的实际区别是什么,因为两者似乎执行相同的响应客户端的操作。
发布于 2013-09-27 10:39:37
当传递对象或数组时,这些方法是相同的,但是res.json()
也会转换非对象,比如null
和undefined
,它们不是有效的JSON。
该方法还使用json replacer
和json 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
这是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);
发布于 2016-05-17 20:32:11
正在查看发送的报头...
res.send使用内容类型:text/html
res.json使用内容类型:应用程序/json
edit: send实际上根据给定的内容改变了发送的内容,所以字符串是以text/html的形式发送的,但是如果您给它传递一个对象,它就会发出application/json。
发布于 2020-06-04 22:23:17
res.json
强制将参数传递给JSON。res.send
将接受一个非json对象或非json数组并发送另一个类型。例如:
这将返回一个JSON编号。
res.json(100)
这将返回一个状态代码,并发出使用sendStatus的警告。
res.send(100)
如果您的参数不是JSON对象或数组(null、undefined、boolean、string),并且您希望确保将其作为JSON发送,请使用res.json
。
https://stackoverflow.com/questions/19041837
复制相似问题