【问题标题】:Cookie not being set locally with Express and React没有使用 Express 和 React 在本地设置 Cookie
【发布时间】:2020-10-22 23:07:38
【问题描述】:

我有一个在 localhost:8181 运行的 ExpressJS 应用程序和一个在 localhost:3000 运行的 ReactJS。在我的 Express 应用程序中,我使用 cookie-session 来生成 cookie。 Express 应用如下所示:

const express = require('express');

const cookieSession = require('cookie-session');
const { v4: uuid } = require('uuid')

const app = express();

app.use(express.json())

app.use(cookieSession({
  name: 'shortlinks',
  keys: [process.env.SESHSECRET],
  maxAge: 30 * 24 * 60 * 60 * 1000 // 30 days
}))


app.use(function(req, res, next) {
  console.log(`${req.method} ${req.url}`);
  req.session.id = (req.session.id || uuid());
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', '*');
  next();
})

app.get(
  '/api/links',
  (req, res, next)=> {
    res.json(readDb());
    next();
  }
)

在我的 React 应用程序中,我正在向 Express 应用程序发出简单的 GET 和 POST 请求。它们看起来像这样:

export async function getLink(id) {
  const response = await fetch(`${LINKS_URL}/${id}`, { withCredentials: true, credentials: 'include' });
  const json = await response.json();
  return json;
}

export async function createLink(url) {
  if (!url) return;
  const response = await fetch(LINKS_URL, {
    withCredentials: true,
    credentials: 'include',
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ long_url: url })
  });
  const json = await response.json();
  return json;
}

在 Chrome 中,当我检查网络响应时,我看到响应标头中设置了 cookie:

Set-Cookie: shortlinks=eyJpZCI6IjkxNDg0MTFjLTI5MTAtNGQ5Ni04ZTdhLTZlMzAyZTQ4NzljNiJ9; path=/; expires=Sat, 21 Nov 2020 00:39:18 GMT; httponly
Set-Cookie: shortlinks.sig=kz0vL2oUQ9KYsDrROkLasxV762w; path=/; expires=Sat, 21 Nov 2020 00:39:18 GMT; httponly
X-Powered-By: Express

但是当我在 Chrome 中的应用程序 -> 存储 -> Cookies 下检查 cookie 时,我没有看到任何 cookie。

到目前为止我已经尝试过(这些都不起作用):

  • 通过 127.0.0.1:3000 而不是 localhost:3000 访问 React
  • 修改/etc/hosts 以将localhost 映射到通用www.localexample.com URL
  • 在我的 React 应用中修改 fetchs(添加/删除/更改 credentials 和 withCredentials 参数)
  • 尝试其他浏览器

我还能尝试什么?我的想法已经用完了。

【问题讨论】:

    标签: node.js reactjs express cookies


    【解决方案1】:

    在网络选项卡中检查的 cookie 中没有找到带有警告的相同站点吗?

    最近,浏览器引入了一个新规范,samesite。

    samesite 有 3 个选项:Lax、None 和 Strict。

    以前,None 是默认设置,但现在 Lax 是默认设置。

    要提供无选项,您需要与 https 通信,并且您可能需要在本地主机上使用 SSL 来执行此任务。

    有关 Samesite 的更多信息,请查看下方。

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite

    [另外]

    • 支持可能因浏览器而异
    • 检查 cookie 域 - localhost 或 127.0.0.1 [带端口]:localhost 和 127.0.0.1 不同。

    【讨论】:

      【解决方案2】:

      我找到了答案here。我将标头 res.header('Access-Control-Allow-Credentials', 'true'); 添加到我的 Express 应用程序中,并将 credentials: 'include' 添加到我的 fetch 请求中,现在我在 Chrome 中看到了 cookie。

      【讨论】:

        猜你喜欢
        • 2019-10-29
        • 1970-01-01
        • 2016-08-17
        • 1970-01-01
        • 2021-11-18
        • 2021-04-04
        • 1970-01-01
        • 2020-12-05
        • 2020-05-31
        相关资源
        最近更新 更多