redux Cookie不是在浏览器中设置,而是在 Postman 中设置(Express js)

qyyhg6bp  于 2023-08-05  发布在  Postman
关注(0)|答案(1)|浏览(104)

我正在从后端API发送cookie(仅HTTP cookie)。当我使用postman发送请求时,cookie设置在头部(Set-Cookie)中,但当我尝试使用redux从前端发送请求时,cookie不会出现在浏览器cookie
browser image

Postman image

respond header有cookie image of the respond header

userController.js

// Public
// /users/login GET
// auth user
const authUser = asyncHandler(async (req, res) => {
  const { email, password } = req.body;
  if (!email || !password) {
    res.status(403);
    throw new Error("email or password empty");
  }
  const user = await User.findOne({ email });
  if (!user) {
    res.status(404);
    throw new Error("user not found");
  }

  if (bcrypt.compareSync(password, user.password)) {

    //generate jwt token and send it  
    genToken(res, user._id);

    res.status(200).json({
      message: "User logged in",
      user: {
        id: user._id,
        name: user.name,
        email: user.email,
      },
    });
  } else {
    res.status(401);
    throw new Error("email or password not correct");
  }
});

字符串

genToken.js

const genToken = (res, userId) => {
  const token = jwt.sign({ userId }, process.env.JWT_SECRET, {
    expiresIn: "30d",
  });

  // set jwt hhtp cookie on the server
  res.cookie("jwt", token, {
    httpOnly: true,
    secure: false, //////////////// development only
    sameSite: "strict",
    maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days,
  });
};

还原/auth的端点

login: builder.mutation({
      query: (data) => ({
        url: `${USERS_URL}/auth`,  // USER_URL=/users
        method: "POST",
        body: data,
      }),
    }),


我使用扩展moesif禁用了浏览器的CORE
并安装了“cors”包
server.js

import express from "express";
import cors from "cors";

const app = express();

var corsOptions = {
  origin: "*",
  optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204,
  credentials: true,
};
app.use(cors(corsOptions));


但没有成功

uqcuzwp8

uqcuzwp81#

成功了。
首先将origin设置为“http://localhost:5173”,并在redux查询中将凭据设置为“include”,在token选项中将sameSite设置为“lax”,并禁用灭绝

相关问题