无法设置标题
问题描述:
我有一些基本的身份验证在使用时抛出控制台错误的路线。无法设置标题
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
at ServerResponse.header
只有当“if”语句为真(if语句内的代码运行)时才会发生。当它不运行时,我没有收到任何错误,并且“主页”视图呈现没有错误。
routes.get('/scan', (req, res, next) => {
const orderID = req.query.order;
const token = req.query.token;
if (!hasAccess(token))
res.status(401).send('Unauthorized');
res.render('home', {order});
});
答
您应该将res.status(401).send('Unauthorized');
后添加return;
以避免发送重复的响应。
答
当您尝试响应您的请求一次以上时,会引发此错误。
为了避免这种错误,发送响应时应该为return
,所以函数不会继续。
你的情况:
routes.get('/scan', (req, res, next) => {
const orderID = req.query.order;
const token = req.query.token;
if(!hasAccess(token))
return res.status(401).send('Unauthorized');
return res.render('home', {order});
});
更新你的代码'res.status(401)后返回。发送(“擅自”);'不然你会试图发送一个响应和渲染页面的每时间。 – Ken