【问题标题】:Set cookies are present in Postman but not in Axios设置的 cookie 在 Postman 中存在,但在 Axios 中不存在
【发布时间】:2021-12-12 05:41:55
【问题描述】:

我正在编写一个前端应用程序,但在将令牌设置为浏览器中的 cookie 时遇到了困难。

后端托管在heroku中,前端运行在本地主机上

我对 React 的要求:

export const axiosConfig: AxiosRequestConfig = {
  withCredentials: true,
  headers: {
    "content-type": "application/json"
  },
};

export const login = async (data: UserLoginData): Promise<UserLoginResponse> => {
  const res = await axios.post<UserLoginResponse>(API_URL + "/login", data, axiosConfig);

  return res.data;
};

快速设置:

app.use(cookieParser());
app.use(cors({ credentials: true, origin: "http://localhost:3000" }));
///
...
///

export const login = async (request: Request, res: Response, next: NextFunction): Promise<void> => {
  try {
    if (isBodyEmpty(request))
      throw new Error();

    const { email, password } = request.body;

    if (!(email && password)) {
      sendFailResponse(res, 400, "All input is required");
      return;
    }

    const user = await User.findOne({ email });
    if (user && (await bcrypt.compare(password, user.password))) {
      user.token = await createToken(user._id, email);
      res.cookie("token", user.token, { maxAge: 900000, httpOnly: true });

      res.status(200).send(constructResponse("Success", user));
      return next();
    }
    sendFailResponse(res, 400, "Invalid Credentials");
    
  } catch (error) {
    sendFailResponse(res, 400, error.message);
  }
};

邮递员的回应:

后端仓库:https://github.com/simsta6/botique

【问题讨论】:

标签: node.js reactjs express


【解决方案1】:

基于Axios documentation,凭据的 axios 配置是 withCredentials: true,而不是 credentials: 'include'(为 fetch 定义)。我没有确认这是您的问题的原因。

请注意,如果您使用HttpOnly 选项 (MDN) 设置它们,您将无法在前端访问 cookie。

注意,您永远无法在客户端访问 Set-Cookie 标头。此标头列为forbidden,并被网络浏览器过滤掉。

【讨论】:

  • 我更改为` withCredentials: true, headers: { "content-type": "application/json", },` 我也在服务器端添加了:res.cookie("token", user.token, { sameSite: "none", httpOnly: true, secure: true });res.headers["set-cookie"] 未定义
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-07-27
  • 2019-07-05
  • 1970-01-01
  • 1970-01-01
  • 2018-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多