Content-Type header not being set with Angular $http

后端 未结 5 2110
逝去的感伤
逝去的感伤 2021-02-15 14:23

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.d         


        
相关标签:
5条回答
  • 2021-02-15 15:05

    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?

    0 讨论(0)
  • 2021-02-15 15:05

    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);
    
    0 讨论(0)
  • 2021-02-15 15:06

    Than you very much "Liran B " your fix worked like a champ for me.... issue was bugging me from several hours....

    var req = {
                    method: 'GET',
                    url: '<your url here>',
                    //headers: {
                    //    'Content-Type': 'application/json;charset=utf-8'
                    //},
                    data: ""
                };
    
      $http(req);
    
    0 讨论(0)
  • 2021-02-15 15:13

    I face the same issue, while setting the headers. we need to send data parameter in the $http request like this

    $http({
        method: 'POST',
        headers: { 'Content-Type': 'application/json},
        data: {},
        url: url
    }); 
    

    we can send blank data also. it will work fine.

    0 讨论(0)
  • 2021-02-15 15:22

    My problem was that I was setting the data variable to an object instead of a string.

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

    Once I changed it to data:'key1=value1&key2=value2' it worked fine. There was also a backslash in there that I had to manually put in the %5c code for.

    0 讨论(0)
提交回复
热议问题