Node.js —— express中 res.json( )和 res.send( )

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);
  • 13
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值