无法设置标题

我有一个基本的身份validation在使用时抛出一个控制台错误的路线。

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

你应该添加一个return; 在你的res.status(401).send('Unauthorized'); 避免发送重复的回复。

当您尝试响应您的请求一次以上时,会引发此错误。

为了避免这种错误,发送响应时应该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}); });