Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Content-Type header not being set with Angular $http

I'm trying to make a cross-origin POST request using Angular $http with the following code.

//I've tried setting and removing these http config options
$http.defaults.useXDomain = true;
delete $http.defaults.headers.common['X-Requested-With'];
$http.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded';

//Basic request, with some private headers removed
return $http({
    method: 'POST',
    //withCredentials:true,
    headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
    params: params,
    url: url
});

The preflight OPTIONS request gets a 200 OK, but the subsequent POST receives a 400 Bad Request response. Looking at the trace in Chrome's debug window, I do not see a Content-Type: application/x-www-form-urlencoded; charset=UTF-8 header for the POST. I assume this is why the the server is returning a Bad Request response.

I'm setting some other custom headers that I have omitted form the code above, and they are being sent and displayed fine.

I should also mention that I can make this request using the Advanced Rest Client app for Chrome and receive the correct response. (An access token)

I have also tried just doing a straight-up XMLHttpRequest(), but I get the same errors.

Any insight on why my Content-Type header is not being set?

like image 491
user3783608 Avatar asked Jul 22 '14 18:07

user3783608


2 Answers

I'm not sure the Content-Type header will be sent if you are NOT sending any data. Add a data object and try it:

return $http({
    method: 'POST',
    //withCredentials:true,
    headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
    data: data,
    url: url
});

Also, usually with a post you use data instead of params (get).

You can also refer to this SO question that has some more info on how to transform the data if you need to: How can I post data as form data instead of a request payload?

like image 58
lucuma Avatar answered Oct 07 '22 02:10

lucuma


The 'Content-Type' header is not being added to the request if the data property is undefined, you can send empty string as data "" for example.

 var req = {
                method: 'GET',
                url: '<your url here>',
                //headers: {
                //    'Content-Type': 'application/json;charset=utf-8'
                //},
                data: ""
            };
  $http(req);
like image 29
Liran Barniv Avatar answered Oct 07 '22 01:10

Liran Barniv