-1

I am implementing a token based authentication and I need to access the token I have set when i check if the user is authenticated.

I am using this method to check if the user is authenticated:

function isAuthenticated(req, res, next) {
    const token = req.headers['authorization'];
    console.log(token);
    if (token) {
        req.token = token;
        next();
    } else {
        res.sendStatus(401);
    }
}

The console.log(token) prints out [object Object] how can I convert this to a json object?

The token is generated with the jsonwebtoken module this way:

jwt.sign({ user_id: user.user_id }, config.app.secretKey, { expiresIn: 60 * 60 * 24 * 7 }, (err, token) => {
    return res.send(token);
});
4
  • Try console.log(req); Commented Feb 6, 2022 at 14:06
  • If you change console.log(token) to console.log(typeof token) what does the console the show? string or object? Commented Feb 6, 2022 at 14:06
  • @t.niese appearently string Commented Feb 6, 2022 at 14:08
  • 6
    Then the value stored in req.headers['authorization'] is a string with the contents [object Object]. Due to that the problem is at an earlier stage in the whole process. Somewhere the authorization header is set incorrectly. Commented Feb 6, 2022 at 14:12

1 Answer 1

2

Unfortunately, the string "[object Object]" doesn't have enough information to recreate back the original object. You'll have to debug the logic and find out why req.headers['authorization'] has such value in the first place.

Sign up to request clarification or add additional context in comments.

Comments