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

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

本文关键字:res 之间 区别 json send js Express      更新时间:2023-09-26

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

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

该方法还使用json replacerjson 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() 方法中 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.charset = this.charset || 'utf-8';
this.get('Content-Type') || this.set('Content-Type', 'application/json');
return this.send(body);

参见:在 expressjs 上res.json源代码。

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

  • 遵守json spacesjson replacer应用设置
  • 确保响应具有utf-8字符集和application/json内容类型

查看发送的标头...

res.send使用content-type:text/html

res.json使用content-type:application/json

编辑:发送实际上会根据给定的内容更改发送的内容,因此字符串作为text/html发送,但是如果您向它传递一个对象,它会发出application/json

res.json将参数强制为 JSON。 res.send将采用非 JSON 对象或非 JSON 数组并发送另一种类型。 例如:

这将返回一个 JSON 编号。

res.json(100)

这将返回状态代码并发出警告以使用 sendStatus

res.send(100)

如果您的参数不是 JSON 对象或数组(nullundefinedbooleanstring ),并且您希望确保它以 JSON 形式发送,请使用 res.json