前言
最近在学习node+express时写一个小小的服务时,真的是发现万事开头难,真的是一脸懵逼,好好学吧,里边烫过的坑记录下来,方便自己学习。
先看看报的错
GET /users/api/getVerificationCode?phone=1233 500 161.231 ms - 48
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:518:11)
at ServerResponse.header (D:\NodesProject\expressDemo\demoApp\node_modules\express\lib\response.js:767:10)
at ServerResponse.send (D:\NodesProject\expressDemo\demoApp\node_modules\express\lib\response.js:170:12)
at done (D:\NodesProject\expressDemo\demoApp\node_modules\express\lib\response.js:1004:10)
at Object.exports.renderFile (D:\NodesProject\expressDemo\demoApp\node_modules\jade\lib\index.js:374:12)
at View.exports.__express [as engine] (D:\NodesProject\expressDemo\demoApp\node_modules\jade\lib\index.js:417:11)
at View.render (D:\NodesProject\expressDemo\demoApp\node_modules\express\lib\view.js:135:8)
at tryRender (D:\NodesProject\expressDemo\demoApp\node_modules\express\lib\application.js:640:10)
at Function.render (D:\NodesProject\expressDemo\demoApp\node_modules\express\lib\application.js:592:3)
at ServerResponse.render (D:\NodesProject\expressDemo\demoApp\node_modules\express\lib\response.js:1008:7)
报错翻译
Cannot set headers after they are sent to the client 发送到客户端后无法设置标头
后来发现是因为每次请求完成后没有释放连接或者return,这样导致多余的响应,所以加一个return,看看我的处理办法
//生成手机登录验证码并返回
router.get('/api/getVerificationCode', (req, res, next) => {
let params = req.query || req.params;
let userPhone = params.phone;
let _res = res;
if (userPhone == undefined || userPhone == "") {
let volaid = {
code: 500,
msg: "手机号不能为空"
}
responseJSON(_res, volaid);
这里如果不加return就会报哪个错,因为会多余的响应
return false;
};
testPhoneNum(_res,userPhone);
let VerificationCode = Math.random().toFixed(6).slice(-6);
userCode[userPhone] = VerificationCode;
let codeData = {
code: 200,
msg: VerificationCode
};
responseJSON(_res, codeData);
});
结束语
我也是刚学,目前了解到这么深,先记下来,后期了解的更深的话会持续更新,方便后续学习。