为了账号安全,请及时绑定邮箱和手机立即绑定

在 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 关注
  • 49 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信