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

2

14

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
Prissie answered 23/8, 2013 at 9:4 Comment(0)
T
3

The $http service config object allows you to override the http header send for a specific request. See config property headers.

This can take a list of headers or a function that return a list of headers. So for the non auth header request make a copy of the default headers remove the header you dont require and then make the request. You can store this for later use.

See $http documentation

Triparted answered 23/8, 2013 at 9:21 Comment(1)
This solution is good for let's say we have only one key, but what if we have multiple custom headers & have multiple such external api calls where we don't need these headers. Can we achieve this using transformRequest ?Jelsma
E
24

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
         }
       }
     )
Elam answered 24/2, 2015 at 18:53 Comment(1)
undefined is the way. Cheers EduardoInsignia
T
3

The $http service config object allows you to override the http header send for a specific request. See config property headers.

This can take a list of headers or a function that return a list of headers. So for the non auth header request make a copy of the default headers remove the header you dont require and then make the request. You can store this for later use.

See $http documentation

Triparted answered 23/8, 2013 at 9:21 Comment(1)
This solution is good for let's say we have only one key, but what if we have multiple custom headers & have multiple such external api calls where we don't need these headers. Can we achieve this using transformRequest ?Jelsma

© 2022 - 2024 — McMap. All rights reserved.