请求标头中包含cookie,但express返回空cookie使用Amazon Load Balancer

问题描述

我正在从前端到快速后端进行fetch。但是将日志req.cookies表示为''(空)。我正在使用cookieParser。

为什么即使浏览器显示了正在发送的cookie,快递还是没有找到cookie?

注意:我正在使用由负载均衡器转发的cookie,该cookie进行身份验证并通过会话发送会话。

前端

    fetch(`${MY_URL}/logout`,{
      credentials: 'include',})

NodeJS

const cookieParser = require("cookie-parser");
app.use(cookieParser());

app.get("/logout",(req,res,next) => {
  console.log(req.headers) // see below
  console.log(JSON.parse(JSON.stringify(req.cookies))); // logs {}
  console.log(JSON.parse(JSON.stringify(req.signedCookies))); // logs {}

  // do stuff with cookie
});

标题

{
  ...
  cookie: ''
}

标题中的Cookie是空字符串

“网络”标签

enter image description here

解决方法

做好了这项工作。最终,解决方案是负载平衡器自动将这些标头无提示地转发到后端。对于我的/logout api,我设置了它们,而不是尝试从标题中获取cookie。像这样:

app.get('/logout',(req,res) => {
  res.cookie("AWSELBSessionCookie","",{
    maxAge: -1,expires: Date.now(),path: '/'
  }

  res.setHeader("Cache-Control","must-revalidate,no-store,max-age=0");
  res.setHeader("Pragma","no-cache");
  res.setHeader("Expires",-1);
  res.redirect("https://my-login-page.com");
})