javascript - Express.js 中 res.send 和 res.json 的区别

标签 javascript node.js http express

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

最佳答案

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

该方法还使用 json replacerjson 空格 应用程序设置,因此您可以使用更多选项格式化 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.send() 方法没有的 res.json() 方法中的代码:

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

关于javascript - Express.js 中 res.send 和 res.json 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19041837/

相关文章:

javascript - 如何在 JavaScript 函数中将文本转换为 HTML 并使用 jest 进行单元测试

javascript - 如何覆盖 res.view.js 文件的 sails.js View Hook ?

javascript - XMLHttpRequest 是否阻止 Content-Disposition 附件?

Javascript - 从输入返回连接而不是变量总和

node.js - 如何替换 ObjectId 引用。与来自 MongoDB 的实际对象一起使用(最好在服务器端)?

ruby-on-rails - 如何通过 HTTParty gem 传递补丁 http 请求参数?

java - 尝试写入文件时出现 Broken Pipe 异常

javascript - 用于 JSON 缩小的 UglifyJs JavaScript API?

javascript - Node 和 MySQL - 解决 "Too Many Connections"问题

javascript - Node.js http 请求返回 body/msg 为空