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'}
})
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
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.
$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.
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.
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() };
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With