首页 > 解决方案 > 将 $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但是,当我遇到问题时,通过我的应用程序执行登录并调用端点。

标签: javascriptnode.jsangularjspassport.js

解决方案


推荐阅读