0

I have the backend of a little register/login project on node, which works fine on postman, I'm doing the frontend using just ejs views, the registration works fine and the login alone too, but if I go to the private page, that works with the jwt token, it doesn't find the token I supposedly got when logged in, console says it's undefined.

This is the verification code.

const jwt = require('jsonwebtoken');

module.exports = function (req,res,next){
    const token = req.header('auth-token');
    console.log(token);
    if(!token) return res.status(401).send('access denied');

    try {
        const verified = jwt.verify(token,process.env.TOKEN_SECRET);
        req.user = verified;

        //see private content
        next();
    } catch (err) {
        res.status(401).send('invalid token');
    }
}

this is the backend of the posts page

const router = require('express').Router();
const verify = require('./verifyToken');

//the verify marks this content as private

router.get('/',verify,(req,res)=>{
    res.render('posts.ejs');
});

module.exports = router;

On postman I fill the token name on the headers, but how can I do something like this on the actual thing?

1 Answers1

0

I searched a bit on this and we cannot pass headers to a url. You can check out this question

Adding http request header to a a href link

When doing an ajax request however we can do attach custom headers and all that. We have full control over the request. I will advise you to use sessions in place of jsonwebtokens. Json Web Tokens are mostly used when using a Front End Framework React, Angular etc because we have to make ajax requests. We than save the token in localStorage and send the token in every subsequent request in the header.

Usman Abdur Rehman
  • 334
  • 1
  • 3
  • 13