NodeJS:发送后无法设置 headers。错误仅发生在 Heroku 上

NodeJS: Can't set headers after they are sent. Error only occurs on Heroku

错误 Error: Can't set headers after they are sent. 仅当我的应用程序部署在 Heroku 上时才会出现。它不会发生在本地主机环境中。

我设法将问题的原因缩小为:

app.get('/*', function(req, res, next) {
    if(req.headers.host.match(/^www/) !== null ) {
        res.redirect('http://' + req.headers.host.replace(/^www\./, '') + req.url);
        console.log(req.url);
    } else {
        next();
    }

    if(!res.getHeader('Cache-Control')) {
        res.setHeader('Cache-Control', 'public, max-age=' + (86400000*7));
    }
});

谁能告诉我为什么代码不能在 Heroku 上运行?它似乎在任何人访问该站点之前就使应用程序崩溃了。

您正在尝试在中间件中设置 header,但您已经在代码中进一步发送了响应。

只需将您的 if 放在呼叫 next 附近:

app.get('/*', function(req, res, next) {
    if(req.headers.host.match(/^www/) !== null ) {
        res.redirect('http://' + req.headers.host.replace(/^www\./, '') + req.url);
        console.log(req.url);
    } else {
       if(!res.getHeader('Cache-Control')) {
          res.setHeader('Cache-Control', 'public, max-age=' + (86400000*7));
       }
        next();
    }  
});