huynhtridung
huynhtridung

Reputation: 43

How to do HTTP Basic Authentication in ionic

I am totally new to ionic. In my project, the API both have a basic authentication. The API then run OK on Postman, but don't know how to do it on ionic. I have research for several articles but they need a lot of step to follow after some steps I get lost.

Here is my code:

app.controller('MainViewController', function ($scope, $http) {
  $http({
    method:"GET",
    url:"my_url"
  }).then(function(categories){
    console.log(categories);
  });
});

I got the error on console:

GET "my_url" 401 (Unauthorized)

Here is the setup on Postman: Postman setup authorization

And the header then: enter image description here Do you know what is the proper way to do this on ionic

Upvotes: 0

Views: 4451

Answers (2)

Dheeraj Gupta
Dheeraj Gupta

Reputation: 380

// Define the string

var string = 'Hello World!';

// Encode the String

var encodedString = btoa(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"

// Decode the String

var decodedString = atob(encodedString);
console.log(decodedString); // Outputs: "Hello World!"

Upvotes: 0

Divyesh Savaliya
Divyesh Savaliya

Reputation: 2740

You can set authorization header in app config as follow

app.run(['$http', function($http) {
  $http.defaults.headers.common['Authorization'] = 'Your key';
}]);

You can also do as follow

$http({
    url : "URL",
    method : 'GET',
    header : {
        Content-Type : 'application/json',    
        Authorization: 'key'
    }
 }).success(function(data){
    alert(data);
 }).error(function(error){
    alert(error);
 })

Upvotes: 2

Related Questions