Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trouble changing request headers in Firefox with AngularJS

My backend requires the 'Content-Type' request header to be exactly 'application/json'. This is a CORS request and everything works fine in Chrome. The exact header, from developer tools network tab source:

Content-Type: application/json

I set this in AngularJS with $http.default.headers.post and it works fine in Chrome. However it doesn't work in Firefox. Firefox sends this instead:

Content-Type: application/json; charset=UTF-8

I tried to change headers by:

  • settings $http.default.headers (for .post, .common)
  • setting custom headers for one request
  • using an $http interceptor

All of those methods work well in Chrome, but not in Firefox. The request contains data.

If I remove the 'Content-Type' header all together, it still is sent, but then it is:

Content-Type: text/plain; charset=UTF-8

(this happens in both Chrome and Firefox).

This leads me to think that the browser forces the header :) How can I circumvent this in Firefox?

like image 954
wiherek Avatar asked Jun 28 '14 09:06

wiherek


1 Answers

Firefox has charset=UTF-8 hard-coded for string payloads.

You may however send a Blob instead:

var r = new XMLHttpRequest();
r.open("POST", ...);
r.send(new Blob(
 [JSON.stringify({a:1})],
 {type:"application/json"}
));

This also works perfectly fine with the angular $http XHR wrapper:

$http({
    method: "POST",
    url: "/echo/json",
    headers: {
        "Content-Type": "application/json"
    },
    data: new Blob([JSON.stringify({
        a: 1
    })])
});

Fiddle

like image 141
nmaier Avatar answered Jan 02 '23 12:01

nmaier