0

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

2 Answers 2

2

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);
 })
Sign up to request clarification or add additional context in comments.

3 Comments

but how can I set basic authen every time request an api this? what if the key change automatically? @divyesh-savaliya
then obviously you have to change key..and key not change automatically...it has some logic on server side
This is the default code of ionic, how can I put that code in to this function? app.run(function($ionicPlatform) { $ionicPlatform.ready(function() { if(window.cordova && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); cordova.plugins.Keyboard.disableScroll(true); } if(window.StatusBar) { StatusBar.styleDefault(); } }); })
0

// 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!"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.