簡體   English   中英

節點express API對Angular $ http調用的響應不佳

[英]Node express API not responding well to Angular $http calls

發生的事情是,當我通過Angular $ http.post()請求從網站訪問登錄路徑時,無法成功登錄到Node API,但是從郵遞員(REST API測試應用程序)進行測試時,它的確運行良好。

這是客戶端代碼(api調用):

 function($http, $scope) {
      $scope.$watch('search', function() {
        fetch();
      });
      $scope.username = 'xxxxxxxxxxxx';
      $scope.password = 'xxxxxxxxxxxxxxxx';        
      function fetch() {
        $scope.details="";
        $http.post("http://apiadress.demo/auth/login?username=" + $scope.username + "&password=" + $scope.password)
          .then(function(response) {
            $scope.details = response.data.state;
          console.log(response);
          });
      }   
    }

此調用產生響應:

{
  "state": "fail",
  "user": null
}

當來自后期客戶響應的相同呼叫時,應注意以下幾點:

{
      "state": "success",
      "user": {
        "_id": "xxxxxxxxxxxxxxxxxxxx",
        "password": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
        "username": "xxxxxxxxxx",
        "__v": 0,
        "created_at": "2016-12-21T21:57:32.663Z"
      }
    }

我的服務器端路由代碼是:

//log in
router.post('/login', passport.authenticate('login', {
    successRedirect: '/auth/success',
    failureRedirect: '/auth/failure'
}));

//responses whit successful login state
router.get('/success', function(req, res){
    res.send({state: req.user ? 'success' : 'fail', user: req.user ?req.user : null});
});

如您所見,當從angular調用api時,用戶似乎已通過身份驗證,但沒有任何數據在重定向中傳遞。

從網站上,您正在通過URL(技術上是針對GET請求)發送用戶數據(用戶名/密碼),但是由於它是POST請求,因此您應將其作為POST數據發送。 這是您要執行的操作:

$http.post("http://apiadress.demo/auth/login", {
    username: $scope.username,
    password: $scope.password
}).then( success, failure );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM