2 回答

TA貢獻1799條經驗 獲得超8個贊
當遇到網絡錯誤或服務器端 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貢獻1921條經驗 獲得超9個贊
您的請求始終執行 .then 塊內的代碼,因為如果收到 HTTP 錯誤代碼,則 fetch 不會失敗。
來自 MDN 文檔:
即使響應是 HTTP 404 或 500,從 fetch() 返回的 Promise 也不會拒絕 HTTP 錯誤狀態。相反,它將正常解析(將 ok 狀態設置為 false),并且僅在網絡故障或如果有任何事情阻止請求完成。
就像文檔所說,您需要檢查 .then 塊中響應對象的屬性是否正確:
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 關注
- 191 瀏覽
添加回答
舉報