Ive been working on a login script for an app with node and express. Unfortunately i keep getting an the error "Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'status')". Ive been trying to figure out what im doing wrong. Could someone please point out why this is happening?
Below is the code for the login script:
//logic for login page
app.post('/api/login', async(req, res)=>{
const {email, password} = req.body
//get user with the passed email and password
const user = await userModel.findOne({email}).lean()
if(!user){
res.json({status:"error", error:"Invalid username / password"})
}
//check if the passwords match
if(await bcrypt.compare(password, user.password)){
const token = jwt.sign(
{
id:user._id,
username:user.username
},JWT_SECRET
)
return res.json({status: "ok", data:token})
}
return res.json({status:"error", error:"Invalid uswername/password"})
})
Also the this how i am making the request to the api
const result = await fetch('/api/login',{
method: 'POST',
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify({
email,
password
})
}).then(res=>{
res.json()
})
if (result.status === 'ok' ){
alert("Success")
console.log(result.data)
}else{
alert(result.error)
}
}```
your problem is how you return the response (that you return it transformed to json() ) and how you capture the errors, I leave you a code example that can help you:
const result = await fetch('/api/login',{
method: 'POST',
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify({
email,
password
})
}).then(res=>{
res
}.catch(error=>{
error
})
if (!result.ok) {
const message = `An error has occured: ${result.status}`;
throw new Error(message);
}
const data = await result.json();
return data;
}