我想用我的前端访问受保护的路由,但是我做不到,只能用邮递员来完成。
我现在尝试将jwt保存在本地存储中,我正在尝试将其设置为标头,但是我很害怕,我仍然做错了什么,无法弄清楚是什么。
这是我的登录名
// Login
router.post("/login", (req, res, next) => {
const username = req.body.username;
const password = req.body.password;
User.getUserByUsername(username, (err, user) => {
if (err) throw err;
if (!user) {
return res.json({
success: false,
msg: "User not found"
});
}
User.comparePassword(password, user.password, (err, isMatch) => {
if (err) throw err;
if (isMatch) {
const token = jwt.sign({
data: user
},
config.secret, {
expiresIn: 604800 // 1 week
}
);
res.setHeader('Authorization', "Bearer " + token);
res.redirect('profile');
} else {
return res.json({
success: false,
msg: "Wrong password"
});
}
});
});
});
// Profile
router.get(
"/profile",
passport.authenticate("jwt", {
session: false
}),
(req, res, next) => {
res.json({
user: req.user
});
}
);
module.exports = router;
Passport.js
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../models/user');
const config = require('../config/database');
module.exports = function(passport){
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
User.getUserById(jwt_payload.data._id, (err, user) => {
if(err){
return done(err, false);
}
if(user){
return done(null, user);
} else {
return done(null, false);
}
});
}));
}
Profile.handlebars
<h1>Welcome on profile</h1>
我真的不知道该怎么做,我主要是在教程上,但是我只是找不到适合的方法。我的尝试都是错误的。