Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send error response in Express/node js?

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})
}

}

like image 496
Yuri Molodyko Avatar asked Dec 03 '22 17:12

Yuri Molodyko


2 Answers

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"})
}
like image 70
Pyroarsonist Avatar answered Dec 30 '22 19:12

Pyroarsonist


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

like image 34
ifarahi Avatar answered Dec 30 '22 18:12

ifarahi