4

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

}

3
  • Isn't it res.status(401).json({"err":error})? Commented Dec 5, 2019 at 11:55
  • 1
    you can send response @ if(!user){ res.sattus(401).send({error: 'Not authorized'});} why do you need to throw error then send res? Commented Dec 5, 2019 at 11:55
  • 2
    try to send only error.message like res.status(401).send(error.message); Commented Dec 5, 2019 at 12:05

3 Answers 3

9

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"})
}
Sign up to request clarification or add additional context in comments.

Comments

7

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

Comments

3

You can send response like the below code.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.