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?
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
– Vitor Couto