Sending body parameter via fetch API
I am trying to send a request asynchronously via javascript to the backend in node, follows the code from the front:
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));
});
}
Or 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 through the front, the body returns null. But when shipping by Insomnia / Postman, it works perfectly.
Error in node:
TypeError: Cannot read property 'passwd' of null
Where am I going wrong?
1 answers
From the error message, you can assume that the error is in this snippet:
passwd !== await user.passwd
First using await
makes no sense, but it won't cause an error, the problem is that the value of user
is equal to null
, and accessing any property of null
throws an exception.
But why does postman work?
Another assumption: it is possible that your backend is not able to decode the message you are sending through fetch
, and how result email
gets the value undefined
, so you can't find user
in your database.
Normally, in a request HTTP
, we send a header
to inform the server what type of encoding we are using in the request payload. Some libraries like Axios
and jQuery
, and also Postman
add this header automatically, but fetch
does not.
Then try to tell your server what the encoding type of your request, add the header like this:
fetch('/auth/authenticate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, passwd })
})