获取期间无法在 try-catch 中捕获 403

Muh*_*Ali 5 javascript put http-status-code-403 reactjs fetch-api

我正在使用 ReactJS 发出放置请求,但是,当我输入错误的电子邮件/密码组合时,即使我试图捕获所有错误并将它们显示在 Chrome 上,我也会将其登录errorDiv

在此处输入图片说明

async connect(event) {
  try {
    const userObject = {
      username: this.state.userName,
      password: this.state.password
    };
    if (!userObject.username || !userObject.password) {
      throw Error('The username/password is empty.');
    }
    let response = await fetch(('someurl.com'), {
      method: "PUT",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(userObject)
    });
    let resJSON = await response.json();
    if (!response.ok) {
      throw Error(resJSON.message);
    }
    console.info(resJSON.message);
    console.info(resJSON.message.auth_token);
    window.location = "/ledger/home";
  } catch (e) {
    document.getElementById("errorDiv").style.display = 'block';
    document.getElementById("errorDiv").innerHTML = e;
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 7

我完全同意@Sagiv,但是有一个快速的解决方法可以做到这一点,尽管这不是建议的方法。在 try 或 Promise.then() 内部,您需要执行此检查。

const res = await fetch();
console.log(res);    // You can see the response status here by doing res.status
Run Code Online (Sandbox Code Playgroud)

因此,通过一些简单的检查就可以解决或拒绝承诺。例如在你的情况下

const res = await fetch();
console.log(res);    // You can see the response status here by doing res.status
Run Code Online (Sandbox Code Playgroud)

我强烈推荐使用axios。关于fetch的问题,可以参考这个链接


Sag*_*b.g 6

根据mdnfetch仅在遇到网络错误时才会抛出。
404(或403) 不是网络错误。

即使响应是 HTTP 404 或 500,从 fetch() 返回的 Promise 也不会拒绝 HTTP 错误状态。相反,它会正常解析(ok 状态设置为 false),并且只会在网络故障或如果有任何阻止请求完成。

例如,404 不构成网络错误。对成功 fetch() 的准确检查包括检查承诺是否已解决,然后检查 Response.ok 属性的值是否为 true