第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決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為。/如果未注冊并且出現(xiàn)錯誤 ( console.log(error)),我想將其更改window.location.href為/Oko/RegisterUser(這是他們已經(jīng)所在的網(wǎng)頁)。目前,當(dāng)register調(diào)用時,/無論是否有錯誤,它都會向用戶發(fā)送消息。RegisterUser如果出現(xiàn)錯誤,有沒有辦法讓用戶留在頁面上?
查看完整描述

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


}


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

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

}


查看完整回答
反對 回復(fù) 2024-01-11
  • 2 回答
  • 0 關(guān)注
  • 185 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號