【问题标题】:Nextjs not reading cookie from Express response all in localhostNextjs 没有从 localhost 中的 Express 响应中读取 cookie
【发布时间】:2022-01-05 02:36:54
【问题描述】:

在我的本地环境中,我正在尝试在登录我的 NextJS 应用程序 (localhost:3005) 后使用来自我的快速后端 (localhost:3020) 的响应设置用户令牌。我可以在服务器的响应中看到 set-cookie,但 getServerSideProps 中的 cookie 始终为空。

我的代码非常基本:

快递后台

 // Cors set up
 cors({
    methods: "GET,HEAD,OPTIONS,POST",
    preflightContinue: false,
    credentials: true,
    origin: [
      "http://localhost:3005",
      ...
    ],
    optionsSuccessStatus: 204,
  })

// Response - can see this cookie in set-cookie
return res.cookie("test", "test1", {
            httpOnly: true,
            sameSite: "none",
            expires,
            domain: "localhost:3005", // tried without this also
          }).redirect("http://localhost:3005/login");

我的 NextJS 应用有以下内容:

 //Login component : on login submit 
  const resp = await fetch(
      `${BACKEND_URL}login?originalUrl=/login`,  // Redirecting back
      {
        headers: new Headers({
          Authorization: "Bearer " + someToken,
        }),
        credentials: "include",
        method: "POST",
        redirect: "follow", // Tried this but did not work
      }
    );
   // resp.redirected is true

// Login component - triggers correctly but no cookies
export const getServerSideProps: GetServerSideProps = async (ctx) => {
  const { req } = ctx;
  const { cookies } = req;
  console.log("cookies", cookies );  // Always {}
  return { props: {} };
};

伙计们,我已经被这个问题困扰了一段时间,似乎我在这里遗漏了一些非常微不足道的东西。我对 NextJs 不是很熟悉,所以这里的任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: node.js express authentication cookies next.js


    【解决方案1】:

    发生这种情况是因为 Chrome SameSite=None + Secure 要求。在 cookie 中将 secure 设置为 true 解决了这个问题。我不必为我的本地环境设置 SSL 证书,只需设置安全即可。

    【讨论】:

      猜你喜欢
      • 2011-03-31
      • 2021-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-21
      • 1970-01-01
      • 1970-01-01
      • 2018-11-14
      相关资源
      最近更新 更多