Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove the default headers just for specific XHR requests in AngularJS?

99% of my ajax calls need a specific "X-API-TOKEN" to authenticate and communicate with my Rails REST API. But I'm also making a call to one thrid party API and I keep getting an error saying "Request header field X-API-TOKEN is not allowed by Access-Control-Allow-Headers."

Everything works fine if I delte the header right before the call, and a work around would be to delete and then re-add after the call, but is there an easier way than this:

    apiToken = $http.defaults.headers.common["X-API-TOKEN"]
    delete $http.defaults.headers.common["X-API-TOKEN"]

    $http(
      method: "GET"
      url: 'http://...}}'
    ).success((data, status, headers, config) ->
    ).error (data, status, headers, config) ->

    $http.defaults.headers.common["X-API-TOKEN"] = apiToken
like image 708
avian Avatar asked Aug 23 '13 09:08

avian


People also ask

How do I remove a header request?

The delete() method of the Headers interface deletes a header from the current Headers object.

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.

Which of these options is correct for setting headers in AngularJS HTTP POST request?

Answer: C is the correct option. The ng-bind directive is used to bind the application data to the HTML view in the AngularJS application.


1 Answers

Set the desire header/headers to undefined like this, then it will not affect the global settings.

$http( {
         method: 'GET',
         url: 'someurl',
         headers: {
           'X-API-TOKEN': undefined
         }
       }
     )
like image 184
Eduardo in Norway Avatar answered Oct 18 '22 10:10

Eduardo in Norway