[英]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
.我正在使用JWT
执行身份验证和授权,并构建 rest apis 以连接ejs
和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.在让一个人通过身份验证后,我正在渲染到该用户的博客页面,但是当我点击添加块时,它说没有传递任何令牌,但是当我使用postman
进行操作时,那么它就没有问题它正在获取令牌。 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.您处理 header 的方式是错误的,根据您提供的有限代码,这似乎是可能出现错误的原因。 Instead of this doing the hard way, try using this gist and implement it as a util function in your frontend不要这样做,而是尝试使用这个要点并将其实现为前端的实用程序 function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.