【发布时间】:2017-08-05 14:11:23
【问题描述】:
我正在使用 Angular 1.6.4、Express 4.15.2 和 express-session。 我试图通过检查 req.session.user 参数的存在来判断用户是否未经授权访问某个路由。如果不是,我想发送 401 响应状态并更改 Angular 中的状态。
问题是我没有得到任何响应对象来检查其状态。 我尝试使用拦截器,注销 error.response.body,真正注销所有内容以找出我丢失响应对象的位置。
这里有一些代码,任何帮助将不胜感激!
快递:
app.get('/update', sessionCheck, function(req, res) {
res.send('session');
});
function sessionCheck(req, res, next){
if(req.session.user) {
next();
} else {
console.log('before');
return res.status(401).send('Unauthorized');
console.log('after');
}
}
角度:
.state('update', {
url: '/update',
views: {
"": {
templateUrl: 'templates/update.html',
controller: function($http) {
return $http.get('/update').then(function(response) {
console.log('Ok response' + response);
}, function(error) {
console.log('Error response' + error.response.body);
});
},
},
"carousel": {
templateUrl: "templates/carousel.html"
},
"footer": {
templateUrl: "templates/footer.html"
}
}
})
【问题讨论】:
-
您在“网络”标签请求中看到了什么?
-
@mehulmpt 添加了屏幕链接到帖子
-
您得到了正确的响应。您在 nodejs 代码中为未经授权的用户发送 401 未经授权,因此它会以这种方式显示在您的网络选项卡中
-
@mehulmpt 好的,但是在控制器中我无法访问响应对象来设置像(response.status == 401)这样的条件。有什么办法吗?
标签: javascript angularjs express