首页 > 解决方案 > 登录后未使用 Fetch 存储的 Cookie

问题描述


我正在使用 REST api 将 React 作为前端,将 Drupal 作为后端来实现身份验证。
从我正在使用的fetch函数中获取数据;登录我/user/login?_format=json从 Drupal 向端点发送请求,结果我得到:uid、name、csrf_token 和 logout_token。

响应消息OK,因为我正确接收到数据,但是cookie没有存储在浏览器中,数据只存储在本地存储中。
我怀疑这会导致一些问题,因为当我提出其他一些请求时,我得到了401 error. 此外,当触发注销端点(/user/logout?_format=json&token=logout_token)时,我得到403 error.

这是代码:

const submitData = async event => {
    event.preventDefault();
    if(captcha == null) {
      setErrorMessage("You did not check the CAPTCHA");
    } else if(username == null || pass == null) {
      setErrorMessage("You did not fill all the necessary fields");
    } else {
      var myHeaders = new Headers();
      myHeaders.append("Content-Type", "application/json");
      myHeaders.append("withCredentials", true);
      myHeaders.append("Access-Control-Allow-Origin", "*");
      
      var raw = JSON.stringify({
        name: String(username), 
        pass: String(pass)
      });

      var requestOptions = {
        method: "POST",
        headers: myHeaders,
        body: raw,
        credentials: "same-origin",
      };

      await fetch(
        process.env.REACT_APP_API_HOST +"/user/login?_format=json",
        requestOptions
      )
      .then((response) => response.text())
      .then((result) => {
        if (JSON.parse(result).current_user){
          window.localStorage.setItem("user-info", result);
          window.location.replace("/registration-landing");
        } else {
          setErrorMessage("An error occured. "+JSON.parse(result).message);
        }
      })
      .catch((error) => console.log("error", error));
    }

我究竟做错了什么?我应该使用axios而不是fetch吗?

标签: reactjsrestcookiesfetch

解决方案


推荐阅读