根据函数是否返回状态代码,你能否制作一个if-else语句来决定回应什么?
的NodeJS / server.js
app.get('/api/videos', function (req, res) {
if(ensureAuthenticated){
Video.find({}, { _id: 0, iframe: 1, title: 1 }, function (err, docs) {
res.json(docs);
});
}else{
Video2.find({}, { _id: 0, iframe: 1, title: 1 }, function (err, docs) {
res.json(docs);
});
});
function ensureAuthenticated(req, res, next) {
if (!req.header('Authorization')) {
return res.status(401).send({ message: 'Please make sure your request has an Authorization header' });
}
var token = req.header('Authorization').split(' ')[1];
var payload = null;
try {
payload = jwt.decode(token, config.TOKEN_SECRET);
}
catch (err) {
return res.status(401).send({ message: err.message });
}
if (payload.exp <= moment().unix()) {
return res.status(401).send({ message: 'Token has expired' });
}
req.user = payload.sub;
req.role = payload.role;
next();
}
只允许登录用户访问我们可以执行的http.get
app.get('/api/videos', ensureAuthenticated, function (req, res)
我如何进行http.get,然后在使用Video.find()进行身份验证之前检查ensureAuthenticated,或者在未经过身份验证时回复Video2.find()?