Express中 res.json 和res.end 及res.send()

今天对某个restful API 进行测试过程发现并发性能很差,吞吐率差了非常多。结果发现是res.end 误用的情况。

参考:express 官方文档 http://www.expressjs.com.cn/4x/api.html#res

现在总结下 express响应中用到常用三种API:

res.send()
res.json()
res.end()

环境

测试环境:express 4.14.1
测试工具:mocha + supertest

1 res.send([body])

发送HTTP响应。
该body参数可以是一个Buffer对象,一个String对象或一个Array。

Sample:

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' });12345

三种不同参数 express 响应时不同行为

1.1 当参数是buffer对象

该方法将Content-Type 响应头字段设置为“application / octet-stream”
如果想Content-Type设置为“text / html”,需使用下列代码进行设置

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

1.2 当参数是是String

该方法设置header 中Content-Type为“text / html”:

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

1.3 当参数是Arrayor 或 Object

Express以JSON表示响应,该方法设置header 中Content-Type为“text / html”

Res.status(500).json({});
res.json([body]) 发送一个json的响应12

1.4 实际测试

sample:

res.send({hello:"word"});
header: 'content-type': 'application/json'
body:{ hello: 'word' }

res.send(["hello","word"]);
header: 'content-type': 'application/json'
body:[ 'hello', 'word' ]

res.send(helloword);
header: 'text/html; charset=utf-8'body:helldworld
body:helldworld(postman 及浏览器测试)

 res.send(new Buffer('helloworld'));
header:'application/octet-stream'
body:<Buffer 68 65 6c 6c 6f 77 6f 72 6c 64>123456789101112131415

2 res.json([body])

发送JSON响应。
该方法res.send()与将对象或数组作为参数相同。 即res.json()就是 res.send([body])第三种情况。同样 ‘content-type’: ‘application/json’。

但是,您可以使用它将其他值转换为JSON,例如null和undefined。(尽管这些技术上无效的JSON)。
实际测试这种条件下的res.body 就是null。
直接发送string ,body直接就是string。

2.1实际测试

Sample:

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

res.json(["hello","word"]);
header: 'content-type': 'application/json'
body:[ 'hello', 'word' ]

res.json({hello:"word"});
header: 'content-type': 'application/json'
body:{ hello: 'word' }

res.json('helloworld');
header: 'content-type': 'application/json'
body:helloworld

res.json(new buffer('helloworld'));
express报错123456789101112131415161718

3 res.end([data] [,encoding])

结束响应过程。这个方法实际上来自Node核心,特别是http.ServerResponse的response.end()方法。
用于快速结束没有任何数据的响应。
如果您需要使用数据进行响应,请使用res.send()和res.json()等方法。

res.end();
res.status(404).end();12

3.1实际测试

Sample:

res.end('helloworld');
helloworld
postman:helloworld
supertest测试:无内容

4 总结

用于快速结束没有任何数据的响应,使用res.end()。
响应中要发送JSON响应,使用res.json()。
响应中要发送数据,使用res.send() ,但要注意header ‘content-type’参数。
如果使用res.end()返回数据非常影响性能。


本文来自 Andy____Li 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/m0_37263637/article/details/79753342?utm_source=copy

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值