繁体   English   中英

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

[英]Call REST API with auth token with React.js

这是调用REST API的尝试,它作为React.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));
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM