Search code examples
javascriptangularjsrestrestful-authentication

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


I'm trying to get data from this website through HTTP get method. This website has basic authentication. The data is in JSON format. This is the rest api website: (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>

Here's the link to my Plunker:

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

Can anyone help?


Solution

  • There are 2 problems in your code.

    1. You have a typo

    In angular.module('myApp', ['base64']), change to module name to myapp

    2. The way you have injected your myapp.controller to myapp module

    Change it to angular.module('myapp', []); You will also need to reorder your code. Check out the Plunker I have created for you.

    Even if you fix the above two problems, you will still face a 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

    Hope this helps