-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);
});
  • Try `console.log(req);` – mplungjan Feb 06 '22 at 14:06
  • If you change `console.log(token)` to `console.log(typeof token)` what does the console the show? `string` or `object`? – t.niese Feb 06 '22 at 14:06
  • @t.niese appearently `string` –  Feb 06 '22 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. – t.niese Feb 06 '22 at 14:12

1 Answers1

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.

Parzh from Ukraine
  • 7,999
  • 3
  • 34
  • 65