I have the express server. When i send a get request, i use a middleware function authorization, for checking a token for this user in database. But, i have an issue: when i'm trying to send the response error, my response send me an empty object, but console.log shows me the error! What am i doing wrong??? Here is my code:
const auth = async(req,res,next)=>{
try {
const token = req.header('Authorization').replace('Bearer ','')
const decode_token = jswt.verify(token,'mytoken')
const user =await User.findOne({"_id": decode_token._id, "tokens.token":token})
if (!user){
throw new Error('Please autorizate')
}
req.token = token
req.user = user
next()
} catch (error) {
console.log(error)
res.status(401).send({"err":error})
}
}
The problem occurs when sending message on receiving error.
If you want to send text message, pass a string to send
function, or use json
function to send JSON object.
Reference: official express site.
Example:
{
console.log(error)
res.status(401).send("Bad login")
}
{
console.log(error)
res.status(401).json({error: "Bad login"})
}
The problem is that the JavaScript Error object cannot be stringified, the error object is not empty you can access the error message on err.message and if you console log the error you will find out that the error object is not empty
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With