【问题标题】:Node express API not responding well to Angular $http callsNode express API 对 Angular $http 调用响应不佳
【发布时间】:2017-01-14 23:37:47
【问题描述】:

发生的情况是,当我通过 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
}

当从 postma 客户端发出相同的调用响应时:

{
      "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 时,重定向中没有传递任何数据... O.o

【问题讨论】:

    标签: javascript angularjs node.js api http


    【解决方案1】:

    您通过 URL(技术上用于 GET 请求)从网站发送用户数据(用户名/密码),但您应该将其作为 POST 数据发送,因为它是一个 POST 请求。以下是您将如何执行此操作:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-29
      • 1970-01-01
      • 1970-01-01
      • 2020-08-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多