亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 React 中注冊用戶帳戶時使用 window.location

在 React 中注冊用戶帳戶時使用 window.location

MMMHUHU 2024-01-11 16:15:59
我正在使用此代碼來注冊用戶: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 => {            window.location.href = '/'        })            .catch(error => console.log(error))            alert("Invalid information, please reenter your details correctly")            window.location.href = '/Oko/RegisterUser'    }它工作正常,我可以注冊用戶,但是,如果用戶帳戶已注冊,我想將其更改window.location.href為。/如果未注冊并且出現錯誤 ( console.log(error)),我想將其更改window.location.href為/Oko/RegisterUser(這是他們已經所在的網頁)。目前,當register調用時,/無論是否有錯誤,它都會向用戶發送消息。RegisterUser如果出現錯誤,有沒有辦法讓用戶留在頁面上?
查看完整描述

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


}


查看完整回答
反對 回復 2024-01-11
?
郎朗坤

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

}


查看完整回答
反對 回復 2024-01-11
  • 2 回答
  • 0 關注
  • 191 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號