Express.js 中 res.send 和 res.json 的区别 [英] Difference between res.send and res.json in Express.js

查看:43
本文介绍了Express.js 中 res.send 和 res.json 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is actual difference between res.send and res.json as both seems to perform same operation of responding to client.

推荐答案

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

The methods are identical when an object or array is passed, but res.json() will also convert non-objects, such as null and undefined, which are not valid JSON.

该方法还使用了 json 替换器json 空间 应用程序设置,因此您可以使用更多选项格式化 JSON.这些选项设置如下:

The method also uses the json replacer and json spaces application settings, so you can format JSON with more options. Those options are set like so:

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方法没有的代码:

This is the code in the res.json() method that the send method doesn't have:

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

这篇关于Express.js 中 res.send 和 res.json 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆