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的问题,可以参考这个链接
| 归档时间: |
|
| 查看次数: |
6898 次 |
| 最近记录: |