1、res.json([body])
发送一个json的响应。这个方法和将一个对象或者一个数组作为参数传递给res.send()方法的效果相同。不过,你可以使用这个方法来转换其他的值到json,例如null,undefined。(虽然这些都是技术上无效的JSON)。

res.json(null);
res.json({user:'tobi'});
res.status(500).json({error:'message'});

2、res.send([body])
发送HTTP响应。body参数可以是一个Buffer对象,一个字符串,一个对象,或者一个数组。比如:

res.send(new Buffer('whoop'));
res.send({some:'json'});
res.send('<p>some html</p>');
res.status(404).send('Sorry, we cannot find that!');
res.status(500).send({ error: 'something blew up' });

对于一般的非流请求,这个方法可以执行许多有用的的任务:比如,它自动给Content-LengthHTTP响应头赋值(除非先前定义),也支持自动的HEAD和HTTP缓存更新。

当参数是一个Buffer对象,这个方法设置Content-Type响应头为application/octet-stream,除非事先提供,如下所示:

res.set('Content-Type', 'text/html');
res.send(new Buffer('<p>some html</p>'));

当参数是一个字符串,这个方法设置Content-Type响应头为text/html:

res.send('<p>some html</p>');

当参数是一个对象或者数组,Express使用JSON格式来表示:

res.send({user:'tobi'});
res.send([1, 2, 3]);

3、res.send( )和res.json( )的区别

当传递对象或数组时,这两个方法是相同的,但是res.json()也会转换非对象,如null和undefined,这些无效的JSON。

该方法还使用json replaceacer和json spaces的设置,因此您可以使用更多选项格式化JSON。 例如:

app.set('json spaces', 2);
app.set('json replacer', replacer);

传递给JSON.stringify()类似:

JSON.stringify(value, replacer, spacing);
// value: 需要格式化的对象
// replacer: stringify 时如何转化属性的规则
// spacing: 锁紧的空格数量

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

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐