javascript - 使用 angular js 和 $http 请求登录不起作用

标签 javascript angularjs rest ionic-framework httprequest

我想使用REST web 服务$httpGET 登录。我正在做的是:

  1. 使用 $http.get 根据用户名和密码获取数据
  2. 存储结果:$scope.getResult=res;
  3. 将其存储在某个变量中:

    var result=$scope.getResult; var username=result.userName;
    var password=result.password;
    var user=this.user; var pass=this.pass;

  4. 之后我将与用户名和密码的 ng-model 进行比较。如果成功,它将重定向到另一个页面,如下所示:

    if (用户名 == 用户 && 密码 == pass) { window.location="/next.html";
    }

下面是我的完整代码,请根据我的情况提出所需的更改。

$scope.login = function () {

  var user = this.user ; // ng-model of username in html page
  var pass = this.pass; //ng-model of password in html page  

  $http.get("http://localhost:17681/api/userRegisters"+user+pass).success(function (res) {

    $scope.getResult = res;

    var result = $scope.getResult;
    var username = result.userName;
    var password = result.password;

    if (username == user && password == pass) {
      window.location="/next.html";
    }

  }

} 

请告诉我应该如何更改我的代码才能做到这一点。

提前致谢:)

最佳答案

用 AngularJS $location 服务替换原始的 window.location 方法。从 $q 服务实现处理程序内部调用 window.location 通常会导致 AngularJS 内部错误。

$http.get("http://localhost:17681/api/userRegisters"+user+pass)
  .then(function onFulfilled(response) {

    $scope.getResult = response.data;

    var result = $scope.getResult;
    var username = result.userName;
    var password = result.password;

    if (username == user && password == pass) {
      //Use this
      $location.path("/next.html");
      //Not this
      //window.location="/next.html";
    }
}).catch ( function onRejected(response) {
    console.log(response.status);
});

有关详细信息,请参阅 AngularJS $location Service API Reference .

Deprecation Notice

The $http legacy promise methods .success and .error have been deprecated. Use the standard .then method instead.1


调试响应

Its gives record via response.data but doesnt give column records. what should be done in order to fetch data ?

服务器端 API 的规范是什么?

生成响应数据的服务器端代码是什么?

为了帮助您,读者需要了解这些内容。否则任何答案都只是猜测。

行业最佳做法是避免将密码作为 URL 的参数发送,因为这存在安全问题。

AngularJS 团队推荐的两个资源: 2


其他资源

关于javascript - 使用 angular js 和 $http 请求登录不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35550746/

相关文章:

javascript - 编写一个使用 .pop 和 .splice 旋转数组的函数

Javascript Mocha 测试 TypeError : x is not a constructor

javascript - 如何将整数数组转换为人力车的 x/y 坐标

javascript - screenX/Y、clientX/Y和pageX/Y有什么区别?

angularjs - 无法使用 Protractor webdriver-manager

ruby-on-rails - 从 ActiveResource 请求中删除 .xml 扩展名

java - 在 REST 资源中接收空值

javascript - 浏览器缓存的部分内容

javascript - Vue 路由继承父属性

rest - Cereal ,随着休息而延伸