Django response code 200 React accept error code

Viewed 292

I have a web app with React frontend and Django rest API backend. when I enter the correct username and password to log in I get the message that should appear when the username or password is wrong.

The React code:

fetch('/token-auth/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({username: this.state.username, password: this.state.password})
    })
      .then(res => res.json())
      .then(json => {
          if (json.ok) {
              localStorage.setItem('token', json.token);
              this.props.notify_login(this.state.username)
          }
          else {
              this.setState({been_failed: true})
          }
      });

So as you can understand the code enters the else block. But the Django server prints the following message saying that the response code is 200.

"POST /token-auth/ HTTP/1.1" 200 286

Does anyone know what can cause such a thing?

2 Answers

I've never used the fetch API, but googling it, it looks like ok is a property of the response, not of res.json(). This is probably why the else block is being executed, res.json().ok will be undefined. Try the following instead:

fetch("/token-auth/", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    username: this.state.username,
    password: this.state.password,
  }),
}).then((res) => {
  if (res.ok) {
    const json = res.json();
    localStorage.setItem("token", json.token);
    this.props.notify_login(this.state.username);
  } else {
    this.setState({ been_failed: true });
  }
});

I managed to fix it by switching to Axios and instead of checking the status code if it failed it goes to the catch

axios( {
    url: '/token-auth/',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    data: JSON.stringify({username: this.state.username, password: this.state.password})
})
  .then(response => {
      localStorage.setItem('token', response.data.token);
      this.props.notify_login(this.state.username)
  })
  .catch(error => {
      this.setState({been_failed: true})
  });
Related