我正在尝试将 Cookie 保存在 meern 的客户端浏览器中

问题描述 投票:0回答:1

前端:

import axios from "axios";
import { useContext, useRef } from "react";
import { useNavigate } from "react-router-dom";
import { BlogsUserStore } from "../store/blogs-user-store";

const Signin = () => {
  const oldEmail = useRef("");
  const oldPassword = useRef("");
  const navigate = useNavigate();
  const { setUser, notifySuccess, notifyError, api } =
    useContext(BlogsUserStore);

  console.log(api);

  const handleSubmit = async (event) => {
    event.preventDefault();
    const email = oldEmail.current.value;
    const password = oldPassword.current.value;
    try {
      const response = await axios.post(
        `${api}/api/user/signin`,
        {
          email,
          password,
        },
        {
          "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        },
        {
          withCredentials: true,
        }
      );
      console.log(response.data);
      setUser([]);
      notifySuccess("Login Successful");
      navigate("/");
    } catch (error) {
      console.error("Error signing in:", error);

      if (error.response && error.response.status === 401) {
        notifyError(error.response.data.message);
      } else {
        notifyError("Incorrect Password");
      }
    }
  };

  return (
    <>
      <div className="container mt-4">
        <form onSubmit={handleSubmit}>
          <div className="mb-3">
            <label htmlFor="email" className="form-label">
              Email address
            </label>
            <input
              type="email"
              className="form-control"
              name="email"
              id="email"
              ref={oldEmail}
              aria-describedby="emailHelp"
            />
            <div id="emailHelp" className="form-text">
              We'll never share your email with anyone else.
            </div>
          </div>
          <div className="mb-3">
            <label htmlFor="password" className="form-label">
              Password
            </label>
            <input
              type="password"
              className="form-control"
              name="password"
              id="password"
              ref={oldPassword}
            />
          </div>
          <button type="submit" className="btn btn-primary">
            Submit
          </button>
        </form>
      </div>
    </>
  );
};

export default Signin;

后端

router.post(
    "/signin",
    checkForAuthenticationCookie("token", "home"),
    async (req, res) => {
        try {
            const { email, password } = req.body;
            const token = await User.matchPasswordAndGenerateToken(
                email,
                password
            );
            // console.log(token);
            res.cookie("token", token, {
                httpOnly: true, // Helps prevent XSS attacks
                maxAge: 24 * 60 * 60 * 1000,
                secure: process.env.NODE_ENV === "production", // Ensure cookies are sent over HTTPS
                sameSite:
                    process.env.NODE_ENV === "production" ? "None" : "Lax",
            });
            console.log(process.env);
            res.status(200).json({ message: "Signin successful" });
        } catch (error) {
            console.error("Error during sign-in:", error);
            if (
                error.message === "User not found" ||
                error.message === "Incorrect password"
            ) {
                res.status(401).json({ message: error.message });
            } else {
                res.status(500).json({ message: "Internal Server Error" });
            }
        }
    }
);

我在我的 React 中使用它。每当我登录时,它不会将我的 cookie 保存到我的客户端浏览器中,我使用了邮递员,它正确地向我发送了 cookie,但当我在 netlify 中部署时却没有。我遇到的主要问题是 cookie 没有保存在我的浏览器中

我使用了 withCredentials 和 Samesite,安全逻辑。它已经将我的数据发送到邮递员,但没有保存浏览器,以便我可以使用它来存储数据

javascript cookies render mern netlify
1个回答
0
投票

您的 axios.post 调用 withCredentials 位于错误的位置。它应该与标头一起位于配置对象内部。

也许这就是问题所在或者

httpOnly 因为具有 secure 属性的 cookie 将 不能在 HTTP 连接上设置。

像这样:

  const response = await axios.post(
      `${api}/api/user/signin`,
      { email, password },
      {
        headers: {
          "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        },
        withCredentials: true,
      }
    );
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.