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

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

问题描述

res.send res.json 之间的实际区别在于似乎执行相同的操作

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

推荐答案

方法在传递对象或数组时是相同的,但 res.json ()还将转换非对象,例如 null undefined 无效的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 replaceacer json spaces 应用程序设置,因此您可以使用更多选项格式化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()方法中的代码有:

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天全站免登陆