如何从具有基本身份验证的 rest api 获取数据?

How to get data from rest api which has basic authentication?

我正在尝试通过 HTTP get 方法从该网站获取数据。该网站具有基本身份验证。数据采用 JSON 格式。 这是其余 api 网站: (https://shoploapi.herokuapp.com/sellers)

// Code goes here
angular.module('myapp', ['myapp.controller']);

angular.module('myapp.controller', ['myapp.service'])
  .controller('testController', function($scope, testService) {

    $scope.posts = {};

    function GetAllPosts() {
      var getPostsData = testService.getPosts();

      getPostsData.then(function(post) {
        $scope.posts = post.data;

      }, function() {
        alert('Error in getting post records');
      });
    }

    GetAllPosts();
  });

angular.module('myapp.service', [])
  .service('testService', function($http) {

    //get All NewsLetter
    this.getPosts = function() {
      return $http.get('https://shoploapi.herokuapp.com/sellers');
    };
  });
angular.module('myApp', ['base64'])
  .config(function($httpProvider, $base64) {
    var auth = $base64.encode("bhupendra7:ice123age456");
    $httpProvider.defaults.headers.common['Authorization'] = 'Basic ' + auth;
  });
<!DOCTYPE html>
<html>

<head>
  <script data-require="angular.js@1.5.0" data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-base64/2.0.5/angular-base64.js"></script>
  <link rel="stylesheet" href="style.css">
  <script src="script.js"></script>
</head>

<body ng-app="myapp">
  <h1>Hello Plunker!</h1>
  <div ng-controller="testController">
    <div>
      <ul>
        <li ng-repeat="post in posts">
          {{post.careof}} {{post.district}} {{post.gender}} {{post.name}}
        </li>
      </ul>
    </div>
  </div>
</body>

</html>

这是给我的 Plunker 的 link:

(https://plnkr.co/edit/7pqljm?p=preview)

有人能帮忙吗?

您的代码中有 2 个问题。

1.你打错了

angular.module('myApp', ['base64'])中,将模块名称更改为myapp

2。您将 myapp.controller 注入 myapp 模块的方式

将其更改为 angular.module('myapp', []); 您还需要重新排序您的代码。查看我为您创建的 Plunker

即使你解决了以上两个问题,你仍然会面临CORS problem from Heroku. Depending on your server-side technology (NodeJS, Rails etc.), you will need to enable it from the server to be able to communicate with your app. You can also look in to JSONP with AngularJS

希望对您有所帮助