2017-06-21 46 views
2

我想通過HTTP獲取方法從這個網站獲取數據。這個網站有基本的認證。數據採用JSON格式。 這是REST API網站: (https://shoploapi.herokuapp.com/sellers如何從具有基本身份驗證的rest api獲取數據?

用戶名: 「bhupendra7」 &密碼: 「ice123age456」

// 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="[email protected]" 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:

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

任何人都可以幫忙嗎?

+0

你有'angular.module一個錯字( '對myApp',[ '的base64'])''做對myApp''myapp'。即使這是正確的,你將面臨另一個問題,testController是「未定義」。讓我知道如果你需要更多的幫助 –

回答

0

你的代碼有兩個問題。

1.你有一個錯字

angular.module('myApp', ['base64']),改變模塊名來myapp

2.你有你注入到myapp.controller模塊myapp

改變它的方式angular.module('myapp', []);您還需要重新訂購代碼。查看我爲您創建的Plunker

即使您解決了上述兩個問題,您仍然會遇到來自Heroku的CORS問題。根據您的服務器端技術(NodeJS,Rails等),您需要從服務器啓用它才能與您的應用進行通信。您還可以查看到JSONP with AngularJS

希望這有助於

+0

Thnak你先生。你能幫我麼。我一直在嘗試很長時間。爲了獲取數據,我需要做些什麼? –

+0

你寫了什麼技術的服務器應用程序? –

+0

服務器應用程序寫在nodejs上。 Mongodb用作數據庫,而Expressjs用作Web框架。 –