【问题标题】:Cookies are not stored on client side in MERN StackCookie 不存储在 MERN 堆栈的客户端
【发布时间】:2022-11-30 14:57:01
【问题描述】:

我想将 jwt 令牌存储为从 express.js(后端)到 react.js(前端)的 cookie。我还安装了 cookie-parser 包并在 main.js 文件(服务器端)中使用它,并使用 res.cookies 创建 cookie。如果我尝试使用邮递员,邮递员会显示 cookie 已成功生成,但如果我尝试使用 react,则不会存储 cookie。

快递代码:

const login = async (req, res, next) => {
  try {
    // geting the user email and the password

    const { userEmail, userPass } = req.body;

    // 1st we are checking that email and the password are existing
    if (!userEmail || !userPass) {
      return next("Plz enter valid email and password");
    }
    console.log(userEmail, userPass);
    // 2nd if usre is existing than password is correct or not

    const user = await userModel.findOne({ userEmail }).select("+password");
    const correct = await user.correctPassword(userPass, user.password);
    if (!userEmail || !correct) {
      return next("Wrong credentials");
    }
    // 3rd if everything is ok then we send the token to the client

    const userToken = signToken(user._id);
    // here we passing the token by using cookie
    res.cookie("jwt", userToken, {
      expires: new Date(Date.now() + 500000),
      httpOnly: true,
      secure: false,
    });
    // console.log(userToken);

    res.status(200).json({
      status: " successfully Login",
    });
  } catch (error) {
    res.status(400).json({
      status: "fail",
      data: next(error),
    });
  }
};

反应代码在这里:

const Login = () => {
  const [userLogin, setUserLogin] = useState({
    userEmail: "",
    userPass: "",
  });

  let name, value;
  const handelInputs = (e) => {
    name = e.target.name;
    value = e.target.value;
    setUserLogin({ ...userLogin, [name]: value });
  };

  const log = async () => {
    const response = await axios.post("/login", userLogin, {
      withCredentials: true,
      credentials: "include",
    })
  };

【问题讨论】:

  • 你能为它写代码吗?

标签: javascript reactjs express cookies mern


【解决方案1】:

根据https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies

JavaScript Document.cookie API 无法访问具有 HttpOnly 属性的 cookie;它只发送到服务器。例如,在服务器端会话中持续存在的 cookie 不需要对 JavaScript 可用,并且应该具有 HttpOnly 属性。此预防措施有助于减轻跨站点脚本 (XSS) 攻击。

只需更改

httpOnly: true

httpOnly: false

【讨论】:

    【解决方案2】:

    如果您不将 cookie 从服务器存储到本地存储

    step-1 发送带有 resp 的令牌,例如:

    ex=
      res.status(200).json({
          status: " successfully Login", token
        });
    

    然后从前端获取令牌。

    const setToken = userLogin.data.token
    
    /*jwtoken is a Name of cookies*/
    
    document.cookie = `jwtoken=${setToken}`;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-22
      • 1970-01-01
      • 2021-01-07
      • 2021-05-28
      • 2021-06-26
      • 2018-07-20
      • 2022-08-07
      相关资源
      最近更新 更多