【问题标题】:Django response code 200 React accept error codeDjango 响应代码 200 React 接受错误代码
【发布时间】:2020-08-31 23:13:34
【问题描述】:

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

React 代码:

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

有谁知道是什么导致了这种情况?

【问题讨论】:

  • 嗨,您能否临时更改您的代码,而不是“if/else”,只需 console.log 该 json 的结果。所以问题会很清楚。看来 json.ok 不是个好主意

标签: javascript django reactjs http jwt-auth


【解决方案1】:

我从未使用过 fetch API,但在谷歌上搜索它,看起来ok 是响应的属性,而不是res.json()。这可能就是为什么 else 块正在被执行,res.json().ok 将是未定义的。请尝试以下方法:

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

【讨论】:

  • 谢谢,我找到了解决方案,但我认为您的解决方案也可以。
【解决方案2】:

我设法通过切换到 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})
  });

【讨论】:

    猜你喜欢
    • 2013-09-08
    • 1970-01-01
    • 2018-05-16
    • 2014-09-21
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多