0

有什么方法可以访问从 express-session 生成的 cookie 吗?我已经生成了一个快速会话 cookie,如下所示

app.use(
session({
  key: "userId",
  secret: "subscribe",
  resave: false,
  saveUninitialized: false,
  cookie: {
    expires: 60 * 60 * 24,
  },
}) );

现在,如果我尝试使用 Universal-cookie 或 js-cookie 库通过 react 访问 cookie,我将无法访问 cookie。

PS:在反应文件中我添加了

Axios.defaults.withCredentials = true;

在后端文件中,我将 cors 配置为

app.use(cors({
origin: ["http://localhost:3000"],
methods: ["GET", "POST"],
credentials: true, }));

但它仍然无法正常工作。

4

1 回答 1

1

当您使用express-session时,发送到前端的唯一 cookie 是connect.sid。默认情况下,它是 httpOnly,这样你就不能在 React 中访问它。要实现它,您需要将 httpOnly 配置更改为 false。

app.use(
  session({
    key: "userId",
    secret: "subscribe",
    resave: false,
    saveUninitialized: false,
    cookie: {
      expires: 60 * 60 * 24,
      httpOnly: false,
    },
  })
);
于 2021-04-21T13:31:13.513 回答