将$ http与angularJS,express和护照一起使用时,req.user未定义

时间:2019-03-10 18:34:22

标签: javascript node.js angularjs passport.js

在angularJS中使用$ http进行API调用时,我遇到了req.user未定义的问题。奇怪的是,如果我使用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 Controller,基本上是在加载此页面时,我呼叫/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端点进行调用。

0 个答案:

没有答案