5

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));
}
4
  • 1
    You are correctly giving method POST, so the error might be in the backend. However, the data you want to send should probably be in the body instead of in the headers. Try body: JSON.stringify({ email: email, password: password }) Commented Jul 19, 2018 at 12:47
  • Doesn't make sense making a POST with no data sent in body Commented Jul 19, 2018 at 12:50
  • It's working now, but now how do I store token's value to do another fetch? @Tholle Commented Jul 19, 2018 at 12:55
  • Could you show us the backend ? Your fetch seems to be right. Here is the way we are using fetch in my company, with a Auth code: fetch(route, {method: 'POST', headers: {'Content-Type': 'application/json', auth: AUTHCODE}, body: JSON.stringify({data})}) The authcode should only be used to confirm the user is coming for a good location. You should use the body for all the other data. Commented Jul 19, 2018 at 12:55

1 Answer 1

6

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));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.