代码之家  ›  专栏  ›  技术社区  ›  soalrib

使用react.js在fetch()时生成的存储令牌

  •  1
  • soalrib  · 技术社区  · 8 年前

    从这段代码中,我得到了一个令牌,我需要将该令牌存储在另一个fetch中以便刷新该令牌,最好的方法是什么?

    我只能访问函数中的变量 .then ...

    我更愿意将令牌存储在编码的cookie中,但我不知道如何处理cookie em react,也不知道如何对它们进行编码或解码。

    componentDidMount() {
      fetch("theURL/api-token-auth/", {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          email: "EMAIL",
          password: "PASS"
        })
      })
        .then(res => {
          if (res.ok) {
            return res.json();
          } else {
            throw Error(res.statusText);
          }
        })
        .then(json => {
          this.setState({
            isLoaded: true,
            token: json
          });
    
          let token = this.state.token;
          console.log("var token: ", token);
        })
        .catch(error => console.error(error));
    }
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   Dupocas    8 年前

    看看localStorage,它是存储令牌的好地方。

    localStorage.setItem('token', 'userToken');

    然后要恢复值,只需执行以下操作: const token = localStorage.getItem('token');

    请深入查看: Web Storage