如何从前端访问状态码

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 但没有用。有什么建议吗?


江户川乱折腾
浏览 135回答 1
1回答

拉莫斯之舞

使用 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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript