开始一个新的 session 会导致错误 - 在将它们发送到客户端后无法设置 headers

Starting a new session causes Error - Cannot set headers after they are sent to the client

开始新的 session 时,例如当我从隐身选项卡访问本地主机时,出现以下错误:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:485:11)
    at ServerResponse.header (E:\Documents\Projects\TypeTest\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (E:\Documents\Projects\TypeTest\node_modules\express\lib\response.js:170:12)
    at done (E:\Documents\Projects\TypeTest\node_modules\express\lib\response.js:1008:10)
    at tryHandleCache (E:\Documents\Projects\TypeTest\node_modules\ejs\lib\ejs.js:261:5)
    at View.exports.renderFile [as engine] (E:\Documents\Projects\TypeTest\node_modules\ejs\lib\ejs.js:461:10)
    at View.render (E:\Documents\Projects\TypeTest\node_modules\express\lib\view.js:135:8)
    at tryRender (E:\Documents\Projects\TypeTest\node_modules\express\lib\application.js:640:10)
    at Function.render (E:\Documents\Projects\TypeTest\node_modules\express\lib\application.js:592:3)
    at ServerResponse.render (E:\Documents\Projects\TypeTest\node_modules\express\lib\response.js:1012:7)
    at E:\Documents\Projects\TypeTest\node_modules\express-ejs-layouts\lib\express-layouts.js:113:20
    at tryHandleCache (E:\Documents\Projects\TypeTest\node_modules\ejs\lib\ejs.js:261:5)
    at View.exports.renderFile [as engine] (E:\Documents\Projects\TypeTest\node_modules\ejs\lib\ejs.js:461:10)
    at View.render (E:\Documents\Projects\TypeTest\node_modules\express\lib\view.js:135:8)
    at tryRender (E:\Documents\Projects\TypeTest\node_modules\express\lib\application.js:640:10)
    at Function.render (E:\Documents\Projects\TypeTest\node_modules\express\lib\application.js:592:3)

我知道多次调用 res.render()res.send() 等会导致此错误,但我在我的代码中找不到任何此类示例。正如我所提到的,这只会在开始一个全新的 session(我认为)时发生,例如在隐身选项卡中访问该网站时。这让我相信它与 cookie-session 可能 re-rendering 页面有关?

即使我将 get 路由器完全留空并且没有发送任何信息,我也会收到同样的错误。这再次让我相信它与我的 session 中间件有关。我也在使用 Passport 进行身份验证,但我认为这不是导致问题的原因。

这是 server.js 的一部分,其中包括 session 中间件。

app.set('view engine', 'ejs');
app.set('views', './views');
app.set('layout', 'layouts/default')
app.use(expressLayouts);
app.use(express.static('public'));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

const flash = require('express-flash');
const cookieSession = require('cookie-session');

app.use(flash());
app.use(cookieSession({
  name: 'session',
  secret: process.env.SESSION_SECRET,
  maxAge: 10000000 * 60 * 60 * 24
}));

const passport = require('passport');
const initializePassport = require('./config/passport');
initializePassport(passport);
app.use(passport.initialize());
app.use(passport.session());

这是我的 Passport 配置。文件

module.exports = function (passport) {
  passport.use(
    new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
      User.findOne().byEmailOrUsername(email).then(user => {
        if (!user) {
          return done(null, false, { message: 'Incorrect email or password' })
        }

        bcrypt.compare(password, user.password, (err, isMatch) => {
          if (err) {
            return done(err);
          } else if (isMatch) {
            return done(null, user);
          } else {
            return done(null, false, { message: 'Incorrect email or password' });
          }
        });
      })
    }));

  passport.serializeUser(function (user, done) {
    console.log('serialize');
    return done(null, user.id);
  });

  passport.deserializeUser(function (id, done) {
    console.log('deserialize');

    return User.findById(id, function (err, user) {
      return done(err, user);
    });
  });
}

如果这个问题措辞过于松散,我深表歉意,但我不确定是什么导致了这个错误。 谢谢

return User.findById(id, function (err, user) {
  return done(err, user);
});

});

您不能将 return 语句用于 return 语句,因为只有 return 语句。 !!!

固定

在我使用

将 HTTP 请求重定向到 HTTPS 服务器之前
app.use((req, res, next) => {
  if (req.protocol === 'http') {
    res.redirect(301, `https://${req.headers.host}${req.url}`);
  }
  next();
})

这导致任何 HTTP 请求被处理两次。我只是在使用隐身选项卡时遇到过这种情况,因为在常规选项卡中,Chrome 在发出请求之前会自动切换到 HTTPS。通过

修复
app.use((req, res, next) => {
  if (req.protocol === 'http') {
    res.redirect(301, `https://${req.headers.host}${req.url}`);
  } else {
    next();
  }
})