javascript - 将 $http 与 angularJS、express 和 passport 一起使用时,req.user 未定义
问题描述
req.user
在 angularJS 中使用 $http 进行 API 调用时,我遇到了一个未定义的问题。奇怪的是,如果我使用 Postman 登录,然后调用我的受保护端点,则已req.user
定义并且身份验证按预期工作。
受保护的端点/activities
(这是使用 $http 时未定义 req.user 的地方):
var isAuthenticated = function (req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect(process.env.BASE_CLIENT_URL + 'login');
}
router.get('/activities', isAuthenticated, activityController.getActivities);
我在成功登录护照后重定向到的 Angular 控制器,基本上在加载此页面时我会调用我的/activities
端点:
angular.module('myApp.view2', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/view2', {
templateUrl: 'view2/view2.html',
controller: 'View2Ctrl'
});
}])
.controller('View2Ctrl', ['$scope', '$http', function ($scope, $http) {
$scope.$on('$viewContentLoaded', function (event) {
$http({
method: 'GET',
url: 'http://localhost:8000/api/activities',
withCredentials: true
}).then(function successCallback(response) {
console.log("Success!");
}, function errorCallback(response) {
console.log("Error");
});
});
}]);
有什么想法吗?我不确定为什么它会通过 Postman 等 API 客户端按预期工作,但不能在我的 angularJS 应用程序中工作,我是否缺少某些标头?
谢谢!
更新:
$http 请求的标头:
accept:"application/json, text/plain, */*"
accept-encoding:"gzip, deflate, br"
accept-language:"en-US,en;q=0.9"
cache-control:"no-cache"
connection:"keep-alive"
cookie:"connect.sid=s%3AFvUCnqkLyGKh6rZh41nU0oXDFiRpu3pZ.74Oit3DNmizkCyvGId1%2F%2FNbLQlichVM6HEHfh3MLS3g"
host:"localhost:8000"
pragma:"no-cache"
referer:"http://localhost:8000/"
user-agent:"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36"
Restlet 的标头:
{"params":{"headers":["Host: localhost:8000","Connection: keep-alive","User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36","Accept: */*","Accept-Encoding: gzip, deflate, br","Accept-Language: en-US,en;q=0.9","Cookie: [331 bytes were stripped]","If-None-Match: W/\"44faa272a8181008d08c6051967c5c38\""],"line":"GET /api/activities HTTP/1.1\r\n"},"phase":0,"source":{"id":819156,"type":1},"time":"496058853","type":159}
通过应用程序运行登录时,可能是登录问题。如果我使用 Postman 登录,然后调用我的/activities
端点,则它是成功的。/activities
但是,当我遇到问题时,通过我的应用程序执行登录并调用端点。
解决方案
推荐阅读
- mongodb - 如何从运行在同一主机上的 Kubernetes 集群内部连接到 MongoDB 数据库?
- c# - 在 C# 中,如何使用 `TryAsync` 的实例?
- html - 为什么 HTML 和 Body 标签在我的编辑器中标记为红色?
- c - 循环直到用户输入在 C 中正确
- javascript - 如何将自定义键添加到猫鼬模式项?
- c++ - 将 unique_ptr 与需要指针指针的接口一起使用到抽象类
- jquery - 如何使用 jQuery 按类名在循环中填充选择控件
- angular - 在 angular-cli 1.7.3 中使用 ng2-charts 的问题
- sql - Presto SQL 查询,用于在算术渐进的时间间隔内计算满足一组条件的行数
- python - “缺少权限”,即使 Bot 在服务器中具有管理员权限和最高角色