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

使用auth token和react.js调用rest api

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

    这是一个尝试呼叫 休息API 作为身份验证令牌 反应.js . 我将令牌请求发送为 POST 它被解读为 GET 有人能帮我吗?

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

    你使用的方法是正确的 POST 所以这不是问题。但是,要发送的数据应位于 body 而不是在 headers .

    componentDidMount() {
      const email = "test@example.com";
      const password = "foobar";
    
      fetch("theURL/api-token-auth/", {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          email,
          password
        })
      })
        .then(res => {
          if (res.ok) {
            return res.json();
          } else {
            throw Error(res.statusText);
          }
        })
        .then(json => {
          this.setState({
            isLoaded: true,
            token: json
          });
        })
        .catch(error => console.error(error));
    }