Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Ignoring $http.default.headers

Tags:

angularjs

Angular v1.3.5

I'm trying to pass serialized data to my API. It requires the Content-Type header to be application/x-www-form-urlencoded; charset=UTF-8;

For POST, I've set this up as follows in my .run:

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8;";

This works great for POST. However, for PUT doing the same is completely ignored.

$http.defaults.headers.put["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8;";

I even tried putting this in the request. The Content-Type was still ignored.

$http({
  method : 'PUT',
  url : SMARTWORX_CONFIGS.APIURL + 'users/' + service.profile.id + '.json',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;'
  },
  data : {
    user : profile
  }
})

I've been forced to solve this by using an interceptor and adding the headers to the config object there. It's quite a hack, but it works.

Am I doing something wrong here?

like image 495
Justin Noel Avatar asked Apr 14 '26 08:04

Justin Noel


1 Answers

After beating my head on the wall some more, I discovered the problem - of my own making.

My app is using tokens for authentication; so, I have an interceptor to inject the token into the headers when needed. I made a mistake with this.

It looked like :

config.headers = config.header || {};
config.headers['X-AUTH-TOKEN'] = result;

It SHOULD have been written like:

config.headers = config.headers || {};
config.headers['X-AUTH-TOKEN'] = result;

Basically, I was blowing out all previous headers.

like image 140
Justin Noel Avatar answered Apr 17 '26 00:04

Justin Noel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!