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('

some html

'
); res.status(404).send('Sorry, we cannot find that!'); res.status(500).send({ error: 'something blew up' });

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

1.1 当参数是buffer对象

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

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

some html

'));

1.2 当参数是是String

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

res.send('

some html

');

1.3 当参数是Arrayor 或 Object

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

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

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:68 65 6c 6c 6f 77 6f 72 6c 64>

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报错

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

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

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

3.1实际测试

Sample:

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

4 总结

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

你可能感兴趣的:(javascript,nodejs)