识别http请求AngularJS

时间:2016-02-21 18:29:14

标签: angularjs http request

我在其他帖子中找不到解决方案。 我试图访问RESTful架构中的数据库。

这就是我想在angularJS中发送http请求的原因。

这是我的代码:

<html ng-app="countryApp">
  <head>
    <meta charset="utf-8">
    <title>Angular.js JSON Fetching Example</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
    <script>
      var countryApp = angular.module('countryApp', []);
      countryApp.controller('CountryCtrl', function ($scope, $http){

          //$http.defaults.headers.common.Authorization = "Basic " + myAuth._base64.encode("admin" + ":" + "changeit");

        // Simple GET request example:
          $http({
            method: 'GET',
            url: 'http://localhost/db/coll'
          }).then(function successCallback(response) {
               $scope.countries = response.data;
               $scope.status = response.status;
               $scope.headers = response.headers;
               $scope.config = response.config;
               $scope.text = response.statusText;
            }, function errorCallback(response) {
               $scope.status = response.status;
               $scope.headers = response.headers;
               $scope.config = response.config;
               $scope.text = response.statusText;
            });
      });
    </script>
  </head>
  <body ng-controller="CountryCtrl">
    <h2>Angular.js JSON Fetching Example</h2>
    <table>
      <tr>
        <th>JSON</th>
        <th>HTTP code</th>
        <th>Headers</th>
        <th>config</th>
        <th>textstatus</th>
      </tr>
      <tr>
        <td>{{countries}}</td>
        <td>{{status}}</td>
         <td>{{headers}}</td>
          <td>{{config}}</td>
           <td>{{textStatus}}</td>
      </tr>
    </table>
  </body>
</html>

我收到了一个http错误代码:401。这是正常的,因为我需要提供登录名和密码。我尝试了很多在网上找不到的解决方案。

如何在angularJS中发送带有登录名和密码的http请求?

谢谢

2 个答案:

答案 0 :(得分:0)

将参数添加到您要发送的请求中:

$http({
   method: 'GET',
   url: 'http://localhost/db/coll',
   params: {login: login, password: password}
})

根据您的角度版本,您可以参考:https://code.angularjs.org/1.2.26/docs/api/ng/service/ $ http

答案 1 :(得分:0)

试试这个:
可能你想要这样的东西

         $http({
            method: 'GET',
            url: 'http://localhost/db/coll'
          }).then(function (response) {

               $scope.data = response.data;

            }, function (response) {
               // error callback
            });
      });

HTML

    <table>
      <tr>
        <th>JSON</th>
        <th>HTTP code</th>
        <th>Headers</th>
        <th>config</th>
        <th>textstatus</th>
      </tr>
      <tr  ng-repeat="d in data">
        <td>{{d.countries}}</td>
        <td>{{d.status}}</td>
         <td>{{d.headers}}</td>
          <td>{{d.config}}</td>
           <td>{{d.textStatus}}</td>
      </tr>
    </table>