繁体   English   中英

res.cookie 没有在 chrome 浏览器中设置 cookie

[英]res.cookie is not setting cookie in chrome browser

在开发中,我有一个在 localhost ( http://127.0.0.1:5500/index.html ) 上运行的简单登录页面和一个在http://localhost:3003上运行的最小快速服务器

我可以看到服务器显示我的access_token正在响应标头中发送,但 chrome 浏览器没有设置它。

响应标头已设置

应用程序面板不显示任何正在设置的 cookie。 应用程序面板为空

这是我的服务器:

const express = require("express");

const cors = require("cors");

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

const { json } = require("express");

const users = require("../users.json");

const SECRET = "1234";

const app = express();

app.use(
  cors({
    origin: "http://127.0.0.1:5500",
    credentials: true,
  })
);

app.use(express.json());
app.use(cookieParser());



app.post("/auth/login", (req, res) => {
  const { email, password } = req.body;

  // add pseudo validation
  if (email !== "********" && password !== "asdfasdf") {
    res.status(403);
    throw new Error("Bad user credentials");
  }

  const token = JWT.sign({ email }, SECRET);
  // console.log("token values:", token);

  res.cookie("access_token", token, {
    maxAge: 3600,
    httpOnly: false,
    secure: false,
    sameSite: "lax",
  });

  res.status(200).json({
    foo: "bar",
  });
});

在前端我使用 fetch:

const loginForm = document.querySelector("#loginForm");

loginForm.addEventListener("submit", login);

function login(evt) {
  evt.preventDefault();
  const email = evt.target.email.value;
  const password = evt.target.psw.value;
  evt.target.reset();

  var headers = new Headers();
  headers.append("Content-Type", "application/json");
  headers.append("Accept", "application/json");

  return fetch("http://localhost:3003/auth/login", {
    method: "POST",
    mode: "cors",
    credentials: "include", // Don't forget to specify this if you need cookies
    headers: headers,
    body: JSON.stringify({ email, password }),
  }).then(
    (res) => {
      console.log(res);
    },
    (err) => {
      console.log(err);
    }
  );
}

我已经尝试在 SO 上针对同一问题发布了多种解决方案:

  1. 在前端添加mode: "cors"credentials: "include"
  2. httpOnly设置为falsesecure设置为false以及服务器上的sameSite: "lax"以通过新的 samesite chrome 浏览器限制

仍然没有任何效果! 我究竟做错了什么?

天啊!! 本地主机!== http://127.0.0.1

我不得不将我的 fetch 调用更改为:

return fetch("http://http://127.0.0.1::3003/auth/login", { //<== this is the main change
    method: "POST",
    mode: "cors",
    credentials: "include", // Don't forget to specify this if you need cookies
    headers: headers,
    body: JSON.stringify({ email, password }),
  }).then(
    (res) => {
      console.log(res);
    },
    (err) => {
      console.log(err);
    }
  );

饼干现在就设置好了。 特别感谢https://github.com/axios/axios/issues/1553#issuecomment-477761247

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM