在 React 中注册用户帐户时使用 window.location

我正在使用此代码来注册用户:


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如果出现错误,有没有办法让用户留在页面上?


MMMHUHU
浏览 52回答 2
2回答

守着星空守着你

当遇到网络错误或服务器端 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))}

郎朗坤

您的请求始终执行 .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))}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5