soalrib
soalrib

Reputation: 599

Call REST API with auth token with React.js

This is a try of call a REST API that as an authentication token with React.js. I'm sending the token request as POST and it's been read as GET, can someone help me please?

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));
}

Upvotes: 5

Views: 15489

Answers (1)

Tholle
Tholle

Reputation: 112787

You are correctly using the method POST, so that's not an issue. However, the data you want to send should be in the body instead of in the headers.

componentDidMount() {
  const email = "[email protected]";
  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));
}

Upvotes: 6

Related Questions