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

soa*_*rib 5 javascript api rest reactjs react-native

这是使用React.js调用REST API作为身份验证令牌的尝试。我发送的令牌请求为 ,它被读取为,有人可以帮助我吗?POSTGET

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));
}
Run Code Online (Sandbox Code Playgroud)

Tho*_*lle 6

您正确使用了该方法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));
}
Run Code Online (Sandbox Code Playgroud)