Random Person
Random Person

Reputation: 115

Custom Headers added in AngularJS only show on Access-Control-Request-Headers

I am trying to use an interceptor to add a custom header to every request in an AngularJS App using the following code:

angular.module('app').factory('httpRequestInterceptor', function () {
    return {
        request: function (config) {
            config.headers['testheader'] = 'testheaderworks';

            return config;
        }
    };
});

angular.module('app').config(function ($httpProvider) {    
    $httpProvider.interceptors.push('httpRequestInterceptor');
});

This code was copied from the answer to this question

Unfortunately, when I examine the resulting requests, I get the following:

Provisional headers are shown

Access-Control-Request-Headers:accept, testheader

Access-Control-Request-Method:GET

Origin:http://localhost:61577

Referer:http://localhost:61577/

User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36

I confirmed this in both the network tab in Chrome and on the server side. Why is the custom header key 'testheader' added to Access-Control-Request-Headers rather than the general headers? What happened to the value? Is there another way to add custom headers to every AngularJS request that avoids this issue?

Upvotes: 5

Views: 1713

Answers (1)

Random Person
Random Person

Reputation: 115

In case anyone reads this and is having the same issue:

The problem was that Angular was making a cross origin request, which the browser was preventing. In order to enable this request I had to enable the header on the server side. In our case (NodeJs) the code to do this was:

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Headers", testheader");
    next();
});

Upvotes: 5

Related Questions