ArticleZip > How To Prevent Angular Js Http Object From Sending X Requested With Header

How To Prevent Angular Js Http Object From Sending X Requested With Header

AngularJS is a powerful front-end framework that allows developers to build dynamic web applications with ease. One common challenge that developers face is preventing the HTTP object from sending the 'X-Requested-With' header.

When making HTTP requests in AngularJS, the framework automatically adds the 'X-Requested-With' header to every request by default. This header is typically used to identify AJAX requests and can sometimes lead to CORS (Cross-Origin Resource Sharing) issues.

To prevent the AngularJS HTTP object from sending the 'X-Requested-With' header, you can use the $httpProvider.defaults.headers.common configuration option. By setting this option, you can customize the default headers that are sent with every HTTP request.

Here's how you can prevent AngularJS from adding the 'X-Requested-With' header:

1. In your AngularJS configuration phase, inject the $httpProvider service:

Javascript

app.config(['$httpProvider', function($httpProvider) {
  // Configure default headers
}]);

2. Inside the configuration function, use the $httpProvider.defaults.headers.common object to remove the 'X-Requested-With' header:

Javascript

app.config(['$httpProvider', function($httpProvider) {
  $httpProvider.defaults.headers.common['X-Requested-With'] = undefined;
}]);

By setting the 'X-Requested-With' header to undefined, AngularJS will no longer include this header in the HTTP requests made by the $http service. This can help prevent CORS issues and allow your application to communicate more effectively with external servers.

It's important to note that removing the 'X-Requested-With' header may have security implications depending on the specific requirements of your application. Make sure to thoroughly test your application after making this change to ensure that it behaves as expected.

In summary, to prevent the AngularJS HTTP object from sending the 'X-Requested-With' header, you can utilize the $httpProvider.defaults.headers.common configuration option in your AngularJS application. By customizing the default headers, you can fine-tune the behavior of your HTTP requests and avoid potential CORS issues associated with the 'X-Requested-With' header.

×