Sending body parameter via fetch API

Asked

Viewed 1,340 times

1

I am trying to send a request asynchronously via javascript to the backend in Node, follow the front code:

if ( window.location.pathname.indexOf('/') != - 1 || window.location.pathname.indexOf('/auth/authenticate') != - 1 ){
    let bntSend = document.querySelector('#sendInfo');
    bntSend.addEventListener('click', async (ev) => {
        let email = document.querySelector('#email').value
        let passwd = document.querySelector('#passwd').value
        console.log(email.toString(), passwd.toString());

            await fetch('/auth/authenticate', {
                method: 'POST',
                body: JSON.stringify({
                    email, 
                    passwd
                })
            })
            .then((data) => { 
               console.log(data);
            }) 
            .catch((err) => console.log(err));

    });

}

The Backend:

router.post('/authenticate', async function(req, res) {
const { email, passwd } = req.body; 
try {
    const user = await User.findOne({ email }).select('+passwd');

    if(passwd !== await user.passwd){
        let message = "Senha incorreta, tente Novamente!";
        return res.render(path.resolve('../frontend/views/layouts/admin/login'), {message})
    } 

    user.passwd = undefined;

    return res
    .send({
        status: 200, 
        data:{
            user, 
            passwdResetToken:generateToken({ id: user._id })
        },
    })  
} catch (err) {

    let message = 'Email ou senha inválidos, tente novamente!';
    return res.render(path.resolve('../frontend/views/layouts/admin/login'), {message})
}
});  

My problem happens when I send the request from the front, the body returns null. But when sent by Insomnia/Postman, it works perfectly.

Error in the Node:

TypeError: Cannot read property 'passwd' of null

Where am I going wrong?

1 answer

2


From the error message, one can assume that the error is in this section:

passwd !== await user.passwd

First to use await does not make any sense, but it will not cause an error, the problem is that the value of user is equal to null, and access any property of null throws an exception.

But why does Postman work?

Another assumption: it is possible that your back-end is not able to decode the message you are sending by fetch, and as a result email gets the value undefined, and so you can’t find the user in your database.

Normally, in a requisition HTTP, we send a header to inform the server the type of encoding we are using in the payload of the request. Some libraries like Axios and jQuery, and also the Postman add this header automatically, but the fetch doesn’t do that.

Then try to inform your server what kind of encoding your request is, add the header this way:

fetch('/auth/authenticate', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ email, passwd })
})
  • Just what we need, thank you very much. And the async that spoke was there by mistake, I had tested to see if change something but forgot to take after haha

Browser other questions tagged

You are not signed in. Login or sign up in order to post.