请求头中不包含Cookie / 服务器端无法读取req.cookies

问题描述 投票:0回答:3

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

我正在使用

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:我的获取代码:

javascript node.js express cookies express-session
3个回答
2
投票

如果您仅使用 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

快速获取 cookie

0
投票

我在 Node-js 上使用 axios (React) + Express-js

在客户端 - 为了从服务器获取 cookie:
只需在 axios 请求中设置

withCredentials: true
,即可使用此配置示例:

const config = {
  headers: {
    "Content-Type": "application/json",
  },
  withCredentials: true,
};

在服务器端 - 为了从客户端获取 cookie:
还需要在axios请求中设置

withCredentials: true

并且需要在服务器上安装
cookie-parser
库:

npm i cookie-parser

导入此库:

const cookieParser = require("cookie-parser");

并使用 cookieParser 中间件:

app.use(cookieParser());

最后,

req.cookies
应该返回您的cookie列表。


0
投票

你有没有得到任何解决方案我现在整个月都陷入这个位置,请告诉解决方案...谢谢你

© www.soinside.com 2019 - 2024. All rights reserved.