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

如何从前端访问状态码

如何从前端访问状态码

江户川乱折腾 2022-11-03 15:13:43
router.post("/login", async (req, res) => {    try    {        const user = await User.findByCredentials(req.body.email, req.body.password, req.body.email)        console.log(user)        if(user === undefined)        {            return res.sendStatus(404)        }        const token = await user.generateAuthToken()        console.log(token)    }    catch(e)    {        console.log(e)       }})我正在从我的后端发送状态码 404。但问题是我不能在我的前端 js 中使用这个状态码。const xhr = new XMLHttpRequest();let form = JSON.stringify({email: $uyeolFormEmail.value,password: $uyeolFormPassword.value});xhr.open("POST", "/login")xhr.setRequestHeader('Content-type', 'application/json')xhr.send(form)console.log(xhr.status)if(xhr.status === 200 || xhr.status === 201){    window.location.href="/takvim"}else if(xhr.status > 299){    window.location.href="/"}我试过 xhr.status 但没有用。有什么建议吗?
查看完整描述

1 回答

?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

使用 XMLHttpRequest 对象,您可以定义在请求收到答案时要执行的函数。


该函数在 XMLHttpResponse 对象的 onreadystatechange 属性中定义:


const xhr = new XMLHttpRequest();

let form = JSON.stringify({

email: $uyeolFormEmail.value,

password: $uyeolFormPassword.value

});


xhr.onreadystatechange = function() {


if (this.readyState == 4 && this.status == 200) {

   window.location.href="/takvim"

 }

else if(this.status > 299)

{

 window.location.href="/"

}


}; 


xhr.open("POST", "/login")

xhr.setRequestHeader('Content-type', 'application/json')

xhr.send(form)


查看完整回答
反对 回复 2022-11-03
  • 1 回答
  • 0 关注
  • 130 浏览
慕课专栏
更多

添加回答

举报

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