Yuri Molodyko
Yuri Molodyko

Reputation: 600

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

}

Upvotes: 4

Views: 11361

Answers (3)

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7969

You can send response like the below code.

res.status({ status: 500 }).json({ message:'internal server error' });

Upvotes: 3

ifarahi
ifarahi

Reputation: 121

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

Upvotes: 7

Pyroarsonist
Pyroarsonist

Reputation: 185

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

Upvotes: 9

Related Questions