How to set $http headers?

I’m trying create a Basic Authentication to $http and to do this I’m trying set headers but I can’t do this.
How could I do this ?

trying this.

var app = angular.module("starter");

app.service("UserLoginAPI", function($http, AppConstants, Base64){
	this.doLogin = function(){
		var _url = AppConstants.webServiceUrl + "/users/testaWS.json";
		var _authdata = Base64.encode('admin' + ':' + 'admin');
		
		var _condigHeader = {
			headers: {
				'Authorization': 'Basic ' + _authdata,
				'Accept': 'application/json; charset=utf-8',
				'Content-Type': 'application/json; charset=utf-8'				
			}
		};

		return $http.post(_url, _condigHeader);   		

	};
});

Exception

OPTIONS http://192.168.1.105/AppPanel/users/testaWS.json (anonymous function) @ ionic.bundle.js:19346sendReq @ ionic.bundle.js:19165serverRequest @ ionic.bundle.js:18877processQueue @ ionic.bundle.js:23399(anonymous function) @ ionic.bundle.js:23415Scope.$eval @ ionic.bundle.js:24678Scope.$digest @ ionic.bundle.js:24489Scope.$apply @ ionic.bundle.js:24783(anonymous function) @ ionic.bundle.js:57605eventHandler @ ionic.bundle.js:12103triggerMouseEvent @ ionic.bundle.js:2870tapClick @ ionic.bundle.js:2859tapMouseUp @ ionic.bundle.js:2932
(index):1 XMLHttpRequest cannot load http://192.168.1.105/GuairaFoods/users/testaWS.json. Response for preflight has invalid HTTP status code 401
VM455:3 XHR Loaded (testaWS.json - 401 Unauthorized - 330.49999992363155ms - 0B)

Take a look at the Docs: https://docs.angularjs.org/api/ng/service/$http.
It’s

$http.post(url, data, [config]);

Try

$http.post(_url, {}, _condigHeader);

Also you might wanna take a look at $httpProvider.defaults.headers.common to set the default header for all your requests.

2 Likes

or the generic way:

$http({
    url: 'http://xxxxxxx',
    method: "POST",
    headers: {
    }
});
1 Like

Solved the problem.

I did

header provider

var app = angular.module('starter');

app.provider('HeaderProvider', function(){
	
	this.$get = function(Base64){
		return {
			getHeader: function(email, senha){
				return {
					'Authorization': 'Basic ' + Base64.encode(email + ':' + senha),
                	'Accept': 'application/json; charset=utf-8',
                	'Content-Type': 'application/json; charset=utf-8' 
				}				
			}
		};
	};
});

finally I created service

var app = angular.module("starter");

app.service("UserLoginAPI", function($http, AppConstants, HeaderProvider, md5){
	this.doLogin = function(User){
		var _url = AppConstants.webServiceUrl + "/users/doLogin.json";		
		var _jsonData = {"User": {"email":User.email, "senha":md5.createHash(User.senha)}};
		var _headers = HeaderProvider.getHeader(User.email, User.senha);
		
            return $http.post(_url, _jsonData, {
        	     headers: _headers,
       	    });		
	};

});
1 Like