400 Bad Request on JWT Authentication

**Hello guys. A little help locating the root cause of this http 400 Error please. Setup is REST API NodeJs +Mysql . So here is a summary of where I am at:

  1. User successfully signed up
  2. JWT tokens successfully generated for user
  3. Model done, POST, GET, DELETE etc works fine.
  4. If I add JWT Token to JSON input and extract from code, it works fine.
  5. When I attempt to retrieve it from the Headers.authorization, then it fails.

See key code sections below :

   Module.exports = (req, res, next){
           const token = req.Headers.Authorization.split(" ")[1];
          //const token2 = req.body.token;  /*this worked!*/
               const decoded = jwt.verify(token, process.env.SECRET);
              req.udata = decoded;
}

**
JSON Object input as follows:

 {
    "project_Id" : 2,
    "lots" : [
        {
            "sn" : "1",
        "lotname" : "Consultancy Project NASA",
        "value" : "N10m",
        "status" : "awarded"
        },
        {
            "sn" : "1",
        "lotname" : "Consultancy Project NASA",
        "value" : "N10m",
        "status" : "awarded"
        }
    ],
    "applicant_Id" : 4,
    "pitch" : "I am the best, you are will be sorry if you do not take me" 
}

And finally, the Postman screen that has tormented me all night :smiley:

Is your JWT token added to the Authorization header as a bearer token?

Authorization: Bearer {jwt_token}

If so then you must do instead:

const token = req.Headers.Authorization.split(" ")[2];

Hey @joint-operations-ph1! Welcome to the Postman community :tada:

In addition to what @jfbriere mentioned, the following should help:
const token = req.header('Authorization').replace('Bearer ', '')

If not, you might want to print out console.log(req.header('Authorization')) to check its value.

Hope this helps!
Please let me know if you have further questions :smiley:

Iโ€™m getting the same error but its weird.

This is my protected middleware and trust me Iโ€™m importing it carefully. Iโ€™m getting the token and as well as req.user in my console.

The problem comes here in the controller part. When I tried to only run the commented part it showed a 400 bad request. So I had to just a res.json(req.user) which seemed to work fine. I donโ€™t know the issue. The database is working.

user

I have spent few days but couldnโ€™t found a solution.

Hey @mission-candidate-46 :wave: Welcome to the Postman Community :tada:

I think the error you are seeing corresponds to the given path โ€œapi/users/profileโ€ is not found.

Can you check where you define your path? e.g.

app.get('/your/path/here', (req, res) => {
// your process 
})