首页 > 解决方案 > 使用 React.js 使用身份验证令牌调用 REST API

问题描述

这是尝试使用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));
}

标签: javascriptreactjsrestapireact-native

解决方案


您正确使用了 method 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));
}

推荐阅读