5

How can I create a global header similar to jQuery using AngularJS?

Something like this:

$.ajaxSetup({
    beforeSend: function (xhr) {
        xhr.setRequestHeader('Requested-With', 'XMLHttpRequest');
        xhr.setRequestHeader('__RequestVerificationToken', 'abc123');
    }
});

Right now I doing this:

$http({
    url: 'mysite.com/',
    method: 'POST',
    data: 'data',
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
1
  • 2
    read section Setting Headers in docs Commented Nov 20, 2013 at 15:17

1 Answer 1

13

Wow ... It was just in front of my face!

Reading the section "Settings headers" as @charlietfl said ... it's really simple.

http://docs.angularjs.org/api/ng.$http

Setting HTTP Headers The $http service will automatically add certain HTTP headers to all requests. These defaults can be fully configured by accessing the $httpProvider.defaults.headers configuration object, which currently contains this default configuration:

To add or overwrite these defaults, simply add or remove a property from these configuration objects. To add headers for an HTTP method other than POST or PUT, simply add a new object with the lowercased HTTP method name as the key, e.g.

$httpProvider.defaults.headers.post = { 'My-Header' : 'value' }

Example Code

var app = angular.module('app', ['app.controller', 'app.service']);

app.config(function ($httpProvider) {
    $httpProvider.defaults.headers.post = { "X-Requested-With": "XMLHttpRequest", "__RequestVerificationToken": $('[name=__RequestVerificationToken]').val() };
}); 
Sign up to request clarification or add additional context in comments.

2 Comments

But we need to do this for all modules. Is there any way to set it globally for all modules?
Didn't test it .... but I think it might work ... module.config(['$httpProvider', function($httpProvider) { $httpProvider.defaults.headers.post = 'my stuff' }]);

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.