0

I am trying to add some custom headers in my api request using AngularJS $http.

buildHttpConfig (url, options) {
  var config = angular.extend({
    method: 'GET',
    headers: {}
  }, options || {});

  config.headers['Content-Type'] = 'application/json; charset=UTF-8';
  config.headers['X-MyCustomHeader'] = {
    "instanceId": "abc",
    "platform": "Web",
    "appId": "efg"
  };
  config.headers.Accept = 'application/json';

  config.url = url;

  return config;
}

getDocumentsToPresent (): ng.IPromise<string> {
  var url = 'https://localhost:8080/services/xyz/myXYZ';
  var deferred = this.$q.defer();
  this.$http(this.buildHttpConfig(url, {method: 'GET'})).then(function (data: any) {
    deferred.resolve(data);
  }, function (err) {
    deferred.reject(err);
  });
  return deferred.promise;
}

Every time I make this request, the custom header automatically added to the 'Access-Control-Request-Headers'. Is there a way to add my custom headers in the global http scope? Thanks.

2
  • Why you dont use config.headers["instanceId"] = "abc" and so on to set headers? Commented Mar 7, 2016 at 20:23
  • because I need to wrap them inside 'X-MyCustomHeader' Commented Mar 7, 2016 at 20:24

1 Answer 1

0

Yup:

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

That's one I added to my app that gets served up with every ajax request I make. Change X-Requested-With to whatever you need.

Sign up to request clarification or add additional context in comments.

3 Comments

actually it doesn't work, I thought it was working before but it turns out it was just some changes on server side that returns different result... I tried everything possible from what you suggested, like setting $httpProvider.defaults.headers.common['X-MyCustomHeader'] = 'XMLHttpRequest'; and $httpProvider.defaults.headers.common['X-MyCustomHeader'] = { custom: 'test' }; and also tried JSON.stringify the object but no luck. Any other suggest? Thanks!
It does in fact work: encosia.com/… under Adding the header to every request automatically and stackoverflow.com/a/31425273/771928 . Not saying that your stuff isn't working, but my answer is the correct one to your question :|.
sorry about that, your answer indeed solved my problem. I believe it is the server side issue. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.