簡體   English   中英

博客 web 中的身份驗證問題,后端使用節點、快遞和 mongoose 和前端使用 ejs

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

我正在使用JWT執行身份驗證和授權,並構建 rest apis 以連接ejsbackend 在讓一個人通過身份驗證后,我正在渲染到該用戶的博客頁面,但是當我點擊添加塊時,它說沒有傳遞任何令牌,但是當我使用postman進行操作時,那么它就沒有問題它正在獲取令牌。 這是我在身份驗證后呈現博客頁面的代碼:

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});
 })

這是我的身份驗證中間件:

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');
    }
}

這是身份驗證后的路線,表示令牌不可用:

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

您處理 header 的方式是錯誤的,根據您提供的有限代碼,這似乎是可能出現錯誤的原因。 不要這樣做,而是嘗試使用這個要點並將其實現為前端的實用程序 function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM