Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add headers to $http for only certain domains

Is it possible to set a header only for specified domains?

The "normal" way of doing this adds that header for all calls, even calls that retrieve HTML templates for example.

$http.defaults.headers.common['Authorization']='...';

So far, other than using an $http interceptor, I can't see any other way, but if you can think of one, I'm curious.

Thanks.

like image 758
Francisc Avatar asked Mar 18 '14 20:03

Francisc


People also ask

How do I add a header to API URL?

Fill out the Create a header fields as follows: In the Name field, enter the name of your header rule (for example, My header ). From the Type menu, select Request, and from the Action menu, select Set. In the Destination field, enter the name of the header affected by the selected action.

Can we send headers in GET request?

For example, to send a GET request with a custom header name, you can use the "X-Real-IP" header, which defines the client's IP address. For a load balancer service, "client" is the last remote host. Your load balancer intercepts traffic between the client and your server.

Can I add custom header to HTTP request?

In the Home pane, double-click HTTP Response Headers. In the HTTP Response Headers pane, click Add... in the Actions pane. In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.

How do I set HTTP headers?

In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name. In the Value box, type the custom HTTP header value.


1 Answers

Creating an interceptor is the way I handle this. I am not sure of another way, so, here's an example anyways. :)

You could create an interceptor that is registered with $httpProvider. Angular will pass the default config object for modification and you could modify the headers there.

Here if a quick example based on the Angular $http doc page:

//register interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
    return {
        // optional method
        'request': function(config) {
            //Figure out which headers you want and set them just for this request.
            config.headers = {"myHeader":"Special"}

            return config;
        }
    };
});

$httpProvider.interceptors.push('myHttpInterceptor');
like image 189
Jonathan Avatar answered Sep 26 '22 15:09

Jonathan