node相关
一.package.json里有dependencies和devDependencies,区别在于dependencies里是生产环境需要的包,devDependencies是开发环境需要的包。一般引一个依赖包时,这个依赖包依赖的包就是dependencies里面的
二.使用nodejs和express开发时,res返回数据有res.send()、res.json()、res.end()三种
先放总结:
用于快速结束没有任何数据的响应,使用res.end()。
响应中要发送JSON响应,使用res.json()。
响应中要发送数据,使用res.send() ,但要注意header ‘content-type’参数。
如果使用res.end()返回数据非常影响性能。
再看详细说明:
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测试:无内容
三、在做点赞功能时,我的逻辑是先将列表表的点赞项的myLike字段+1,然后再将当前点赞项的id push到当前用户表的myLike字段中。但是实际使用中,发现点赞完之后,立即刷新又可以点赞,再刷新还可以点赞。
原因:排查了一段时间,发现是后台接口的问题。我在将列表表的点赞项的myLike字段+1后就直接返回了,这样会导致用户数据还没更新,前端就取了用户的myLike,这时候的myLike数组里不包含刚刚点赞的id
解决:将res.send()放到 当前点赞项的id push到当前用户表的myLike字段中 的回调函数中执行即可

浙公网安备 33010602011771号