我有带有Express的Node.js。我正在使用cookieSession进行身份验证
app.use(cookieSession({
name: 'session',
keys: ['key1','key2'],
// Cookie Options
maxAge: 24 * 60 * 60 * 1000 // 24 hours
}));
还有我的控制器来设置令牌
exports.student_logIn = function(req, res) {
req.session = null;
Student.findOne({ email: req.body.email }, function (err, user) {
if (err) return res.status(500).send('Error on the server.');
if (!user) return res.status(404).send('No user found.');
var passwordIsValid = bcrypt.compareSync(req.body.password_logIn,
user.password);
if (!passwordIsValid){
return res.status(401).send({ auth: false, token: null });
}
var token =
{
userId : jwt.sign({ id: user._id }, config.secret, {
expiresIn: 86400 // expires in 24 hours
})
}
console.log('Creating token '+user._id);
var cookie = req.session;
if (!cookie) {
req.session = token;
console.log('Provided new token');
} else {
console.log('Valid cookie session');
}
res.status(200).redirect('/student_profile');
});
};
将基于令牌发送配置文件数据的主控制器:
exports.student_profile = function(req, res){
var token = req.session.userId;
if (!token){
console.log('Here NO TOKEN!');
return res.status(401).send({ auth: false, message: 'No token provided.'
});
}
jwt.verify(token, config.secret, function(err, decoded) {
if (err){
return res.status(500).send({ auth: false, message: 'Failed to
authenticate token.' });
}
async.parallel({
student: function(callback){
Student.findById(decoded.id,{password:0}).exec(callback);
},
projects: function(callback){
Project.find({student:decoded.id}).exec(callback);
}
}, function(err,results){
if (err) { return next(err); }
if (results.student==null) { // No results.
var err = new Error('Student not found');
err.status = 404;
return next(err);
}
res.render('student_area_profile',{title: 'Student Profile',student
: results.student, projects: results.projects});
});
});
};
当我在同一端口中使用ejs视图时,此代码工作正常。几天前,我决定将前端转换为Angular。当我通过其他端口访问令牌时,在重定向过程中丢失了。我将此代码片段用于CORS:
var cors = require('cors');
app.use(cors());
我收到一条消息“这里没有令牌!”从第二个开始。我将不胜感激。谢谢!