繁体   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