Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent angular.js $http object from sending X-Requested-With header?

Tags:

Angular.js, when accessing a web service using the $http object, automatically adds a X-Requested-With:XMLHttpRequest header to the request.

The web service I am accessing using CORS doesn't support X-Requested-With header, so I tried to eliminate it but I can't acess the $httpProvider object. I get an undefined object error, and if I reference it in the controllers parameters, so that angular injects it I get a "Error: Unknown provider: $httpProviderProvider <- $httpProvider"

So I wonder how can I access the $httpProvider, like it says in the docs (http://docs.angularjs.org/api/ng.$http) to tell angular.js not to send that header...

like image 597
opensas Avatar asked Sep 07 '12 06:09

opensas


People also ask

How do you modify the $HTTP request default Behaviour?

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.

What is $HTTP in AngularJS?

$http is an AngularJS service for reading data from remote servers.

What is interceptor in AngularJS?

This interceptor is called when the $http receives the response from the server. This function receives a response object as a parameter return a response object or a promise. A response interceptor is used to modify the response data or adding a new set of values, calling another module or services call.


2 Answers

angular.module('myModule', [])     .config(['$httpProvider', function($httpProvider) {         delete $httpProvider.defaults.headers.common["X-Requested-With"]     }]) 
like image 171
Justen Avatar answered Nov 13 '22 02:11

Justen


I found that, besides Justen answer, I can also do it on a per request basis like this:

delete $http.defaults.headers.common['X-Requested-With'] 
like image 38
opensas Avatar answered Nov 13 '22 00:11

opensas