【问题标题】:Cookie is not included in request header / Server side cannot read req.cookiesCookie 不包含在请求标头中/服务器端无法读取 req.cookies
【发布时间】:2021-12-30 08:41:18
【问题描述】:

我正在学习并为我的博客网站申请身份验证!

我正在使用express-session 来处理登录。浏览器和服务器会话上的 Cookie 工作正常。

但是,我在服务器端 express 应用上检索 cookie 时遇到问题。我尝试了以下方法:

  • 使用 cookie 解析器,req.cookies 和 req.signedCookies 都返回 [Object: null prototype]。
  • 设置 CORS
  • req.cookie & req.header.cookie 返回undefined
  • 我可以在浏览器网络选项卡中的连接中看到“Cookie”标头。

我的代码/设置如下:

function auth (req, res, next) {
  // Problem: Cannot read browser cookie of HTTP requests.
  console.log('Based on browser', req.cookie, req.cookies, req.signedCookies);
  next();
}

router.get('/', auth, async (req, res) => { // ... }

中间件

app.use(cors({
  origin: ['http://localhost:3000'],
  credentials: true
}));
app.use(cookieParser())  // Also tried with secret option.
app.use(session({
  secret: 'top-secret',
  resave: true,
  rolling: true,
  saveUninitialized: false,
  store: store, // this is working
  cookie: {
    maxAge: 1000 * 60 * 60 * 24 * 14,
    httpOnly: true,
    secure: process.env.NODE_ENV !== 'Development',
    sameSite: process.env.NODE_ENV === 'Development' ? 'lax' : 'none'
  }
}))

提前谢谢你:)

编辑 1:我的获取代码:

【问题讨论】:

  • 您在发出 ajax 请求吗?因为这些默认情况下不传输 cookie。 (编辑:跨域的)
  • 你好 Chris,我使用 fetch API 提出了请求
  • 是的,但我假设来自不同的服务器?这意味着您需要通过将 credentials: include 添加到 fetch 选项来启用 cookie 的传输。 developer.mozilla.org/en-US/docs/Web/API/fetch#syntax
  • 我之前没有包含该选项。但不幸的是,添加该选项并没有解决问题。 :(
  • 你能显示相关的抓取代码吗?

标签: javascript node.js express cookies express-session


【解决方案1】:

如果你只使用 http,你应该考虑两件事:

在客户端请求时的第 1 步: 你应该这样发送请求:

        const req = await fetch("http://localhost:7000/api/auth/login", {
      method: "POST",
      credentials: "include",
      headers: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Credentials": true,
      },
      body: JSON.stringify({
        email: formData.get("email"),
        password: formData.get("password"),
      }),
    });
    const data = await req.json();

快递中的第 2 步:

const allowedOrigins = ["http://localhost:8000"];
    const corsOptions = {
    origin: function (origin, callback) {
   if (allowedOrigins.indexOf(origin) !== -1) {
  callback(null, true);
    } else {
     var msg =
    "The CORS policy for this site does not " +
    "allow access from the specified Origin.";
     callback(new Error(msg), false);
   }
 },
optionsSuccessStatus: 200,
 credentials: true,
 };
app.use(cors(corsOptions));

现在您可以使用 req.cookies.nameOfCookiesWhichYouSendThroughCoockieParser

快速获取 coockies

【讨论】:

  • 谢谢。我意识到 cookie 在除 GET 之外的所有 HTTP 请求下都能正常通过。不知道为什么,但我可以解决这个问题。
  • 当您在第一个请求中获取 cookie 时。您可以访问所有请求方法的 cookie:GET、POST、PUT...您应该设置客户端标头以与其他请求共享 cookie,并且您可能为 cookie 设置了较短的过期时间。
猜你喜欢
  • 2015-10-26
  • 2017-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-06
  • 1970-01-01
相关资源
最近更新 更多