使用React.js用身份验证令牌调用REST API

时间:2018-07-19 12:45:37

标签: javascript reactjs rest api react-native

这是尝试使用 React.js 调用 REST API 作为身份验证令牌的尝试。我正在以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 个答案:

答案 0 :(得分:1)

您正确使用了方法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));
}
相关问题