Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global header for AngularJS post

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'}
})
like image 845
Felipe Miosso Avatar asked Nov 20 '13 14:11

Felipe Miosso


People also ask

How do I add HTTP headers in angular?

Angular 9, Angular 10, Angular 11, Angular 12 We add HTTP Headers using the HttpHeaders helper class. It is passed as one of the arguments to the GET, POST, PUT, DELETE, PATCH & OPTIONS request. To use HttpHeaders in your app, you must import it into your component or service

What is HTTP POST in AngularJS?

AngularJS Http Post ($http.post ()) service In angularjs we use $http service to send or get data from remote http servers using browsers XMLHttpRequest object.

What is the use of HTTP provider in angular?

$http - $httpProvider - service in module ng Overview The $httpservice is a core AngularJS service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequestobject or via JSONP. For unit testing applications that use $httpservice, see $httpBackend mock.

How to add headers for an HTTP method other than post?

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.get = { 'My-Header' : 'value' }. The defaults can also be set at runtime via the $http.defaultsobject in the same fashion.


1 Answers

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() };
}); 
like image 84
Felipe Miosso Avatar answered Oct 10 '22 18:10

Felipe Miosso