When inquiring a remote endpoint, from a javascript application, you are usually performing an http call (GET, POST...) to access specific services, such as getting a content list, login to a protected area or storing a text message just written.

The headers of a HTTP call are critical to the correct interpretation of the call. For example, the header may contain the authentication data, needed to the client to be authenticated and accepted by server.

$http headers, a native tool of AngularJS to inquiry remote endpoints via HTTP protocol, may be set to a global level, i.e. they are inherited by all methods (GET, POST, DELETE, PUT, PATCH), or may be inherited by a single method.

Setting an header

The following example shows the setting of an header for a single request, i.e. only when it is executed (e.g. inside a controller):

  method: 'POST', 
  url: 'http://my-endpoint/login', 
  headers: {'Authorization': 'xxxyyyzzz'}

or when you are using a shortcut to directly run a POST call:

    headers: {'Authorization': 'xxxyyyzzz'}

If you prefer to set a single header for all POST calls, you can do it directly during configuration phase, via $httpProvider or via $http module:

//with the provider, in the app.config():
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
//or directly in the $http: this header will be used also by all calls after this one:
$http.defaults.headers.common['Content-Type'] = 'application/json; charset=utf-8';

Remove header of x-requested-with

AngularJs automatically adds headers of “X-Requested-With” type to the performed calls. This setting may cause errors when trying inquiries to endpoints external to the current domain, e.g. in case the application is hosted by domain http://my-site.com and the contacted endpoint is in the domain http://other-site.com.

Using $httpProvider and $http, you can add or remove headers

Gabriele Mittica

Developer at Corley S.r.l , Website , Git home page , @gabrielemittica , Linkedin profile
Passionate startupper, Cloud developer and amstaff lover. Worldwide geekka traveler!

All articles by Gabriele Mittica


comments powered by Disqus


Follow Us