简体   繁体   English

节点express API对Angular $ http调用的响应不佳

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

What's happening is that I can't get succesfully loged in into the Node API when hitting the login route from the website via Angular $http.post() request, But it does Works pretty well when testing from postman (rest api test application). 发生的事情是,当我通过Angular $ http.post()请求从网站访问登录路径时,无法成功登录到Node API,但是从邮递员(REST API测试应用程序)进行测试时,它的确运行良好。

Here is the client side code (api calls): 这是客户端代码(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);
          });
      }   
    }

this call produces the response: 此调用产生响应:

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

When making the same call from postma client responses the espected: 当来自后期客户响应的相同呼叫时,应注意以下几点:

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

My server side routing code is: 我的服务器端路由代码是:

//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});
});

As you can see the user seems to be authenticeted but no data is being passed on the redirection when the api is called from angular... Oo 如您所见,当从angular调用api时,用户似乎已通过身份验证,但没有任何数据在重定向中传递。

From the website you are sending user data (username/password) through URL (which is technically for GET requests) but you should send it as POST data since it's a POST request. 从网站上,您正在通过URL(技术上是针对GET请求)发送用户数据(用户名/密码),但是由于它是POST请求,因此您应将其作为POST数据发送。 Here is how you would do this: 这是您要执行的操作:

$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