Javascript Django响应代码200反应接受错误代码

Javascript Django响应代码200反应接受错误代码,javascript,django,reactjs,http,jwt-auth,Javascript,Django,Reactjs,Http,Jwt Auth,我有一个带有React前端和Django rest API后端的web应用程序。 当我输入正确的用户名和密码登录时,我会收到当用户名或密码错误时应显示的消息 反应代码: fetch('/token-auth/', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({username: this.state.

我有一个带有React前端和Django rest API后端的web应用程序。 当我输入正确的用户名和密码登录时,我会收到当用户名或密码错误时应显示的消息

反应代码:

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})
          }
      });
如您所知,代码进入else块。但是Django服务器打印以下消息,表示响应代码为200

“POST/token auth/HTTP/1.1”200 286


有人知道是什么导致了这样的事情吗?

我从未使用过fetch API,但通过谷歌搜索,它看起来像是
ok
是响应的属性,而不是
res.json()
。这可能就是执行
else
块的原因,
res.json()。请尝试以下操作:

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

我设法通过切换到Axios来修复它,如果失败了,就转到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})
  });

您好,您是否可以临时更改代码,而不是“if/else”,只需将json的结果记录在console.log中。所以问题会很清楚。看来json.ok不是一个好主意,我找到了一个解决方案,但我认为你的也能奏效。