简体   繁体   中英

authentication problem in blogging web, backend with node, express and mongoose and front end with ejs

I am performing authentication and authorization using JWT and building rest apis to connect ejs and backend . After getting a person authenticated i am rendering to the blogger page of that user but when i clink on add block it says no token is passed but when i am doing it using postman then there is no issue it is getting token then. this is my code of rendering a blogger page after authentication:

router.post('/', async (req, res) => {
    const { error } = validate(req.body);
    if (error) return res.status(400).send(error.details[0].message);
    
    let user = await User.findOne({email:req.body.email});
    if (user) return res.status(400).send("user already registered");
    user = new User(_.pick(req.body,['name','email','password']));
    const salt = await bcrypt.genSalt(10);
    user.password = await bcrypt.hash(user.password,salt);
    await user.save();

    // const token= user.generateAuthToken();
    // res.header('x-auth-tocken',token).send({name:user.name, user:user._id,token:token});
    const token = jwt.sign({_id:this._id},config.get('jwtPrivateKey'));
    let blogs = await blogss.find();
    res.header('x-auth-token',token).render('bhome',{blogs:blogs,user:user});
 })

and this is my auth middleware:

module.exports = function (req ,res, next) {
    const token = req.header('x-auth-token');
    console.log(req.header('x-auth-token'));
    console.log('me here in auth');
    if(!token) return res.status(401).send('access denied because there is no token');
    try {
        const decoded = jwt.verify(token,config.get('jwtPrivateKey'));
        req.user = decoded;
        next();
    } catch (ex) {
        res.status(400).send('invalid taken');
    }
}

and this is the route after authentication which says token is not availible:

router.get('/addblog', auth, (req, res)=>{
    res.render('addblog');
});

The way you are handling the header is wrong and based on the limited code you provided, it seems to be the reason for possible error. Instead of this doing the hard way, try using this gist and implement it as a util function in your frontend

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM