Search code examples
javascriptnode.jsajaxhttp-status-codes

How can I access the status code from front end


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

I am sending the status code 404 from my backend. But the problem is I can't use this status code in my frontend 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="/"
}

I tried xhr.status but it didn't worked. Any advices?


Solution

  • With the XMLHttpRequest object you can define a function to be executed when the request receives an answer.

    The function is defined in the onreadystatechange property of the XMLHttpResponse object:

    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)