2 回答

TA貢獻(xiàn)1799條經(jīng)驗 獲得超8個贊
當(dāng)遇到網(wǎng)絡(luò)錯誤或服務(wù)器端 CORS 配置錯誤時, fetch() Promise 將拒絕并返回 TypeError [developer.mozilla.org]
您需要使用 res.ok 來檢查 HTTP 錯誤
register = event => {
console.log(this.state.credentials);
fetch('http://api.herokuapp.com/account/users/', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(this.state.credentials)
}) .then(res => {
if(res.ok) {
window.location.href = '/'
} else {
alert("Invalid information, please reenter your details correctly")
window.location.href = '/Oko/RegisterUser'
}
})
.catch(error => console.log(error))
}

TA貢獻(xiàn)1921條經(jīng)驗 獲得超9個贊
您的請求始終執(zhí)行 .then 塊內(nèi)的代碼,因為如果收到 HTTP 錯誤代碼,則 fetch 不會失敗。
來自 MDN 文檔:
即使響應(yīng)是 HTTP 404 或 500,從 fetch() 返回的 Promise 也不會拒絕 HTTP 錯誤狀態(tài)。相反,它將正常解析(將 ok 狀態(tài)設(shè)置為 false),并且僅在網(wǎng)絡(luò)故障或如果有任何事情阻止請求完成。
就像文檔所說,您需要檢查 .then 塊中響應(yīng)對象的屬性是否正確:
register = event => {
fetch('http://api.herokuapp.com/account/users/', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(this.state.credentials)
}) .then(res => {
if(res.ok) {
window.location.href = '/'
}else{
alert("Invalid information, please reenter your details correctly")
window.location.href = '/Oko/RegisterUser'
}
}).catch(error => console.log(error))
}
- 2 回答
- 0 關(guān)注
- 185 瀏覽
添加回答
舉報