首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Express.js中res.send与res.json的区别

Express.js中res.send与res.json的区别
EN

Stack Overflow用户
提问于 2013-09-27 10:38:16
回答 3查看 142K关注 0票数 232

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-09-27 10:39:37

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

该方法还使用json replacerjson spaces应用程序设置,因此您可以使用更多选项格式化JSON。这些选项的设置如下:

代码语言:javascript
复制
app.set('json spaces', 2);
app.set('json replacer', replacer);

并像这样传递给JSON.stringify()

代码语言:javascript
复制
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方法没有的代码:

代码语言:javascript
复制
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()

代码语言:javascript
复制
this.charset = this.charset || 'utf-8';
this.get('Content-Type') || this.set('Content-Type', 'application/json');

return this.send(body);
票数 241
EN

Stack Overflow用户

发布于 2016-05-17 20:32:11

正在查看发送的报头...

res.send使用内容类型:text/html

res.json使用内容类型:应用程序/json

edit: send实际上根据给定的内容改变了发送的内容,所以字符串是以text/html的形式发送的,但是如果您给它传递一个对象,它就会发出application/json。

票数 20
EN

Stack Overflow用户

发布于 2020-06-04 22:23:17

res.json强制将参数传递给JSON。res.send将接受一个非json对象或非json数组并发送另一个类型。例如:

这将返回一个JSON编号。

代码语言:javascript
复制
res.json(100)

这将返回一个状态代码,并发出使用sendStatus的警告。

代码语言:javascript
复制
res.send(100)

如果您的参数不是JSON对象或数组(null、undefined、boolean、string),并且您希望确保将其作为JSON发送,请使用res.json

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19041837

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档