Search code examples
javascriptaxiosxmlhttprequesthttp-headers

Why Content-Type "appication/json" is not Working when method is "GET" in axios?


Method is "GET". Content-Type is "application/json".

this is not working. (Response is 415(HTTP code).)

var config =    {
     headers : { 
        "Accept": "application/json",
        "Content-Type": "application/json",
     }
   };

axios.get('http://192.168.2.2:90/api/pagetwo?size=10&page=1', config)
.then((res) => {
  console.log(res);
});

but this is working. following :

var xhr = new XMLHttpRequest();                               // only XMLHttpRequest.
var url = "http://192.168.2.2:90/api/pagetwo?size=10&page=1";
xhr.open("GET", url, false);                                  // false is "async"
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
  if (this.readyState === XMLHttpRequest.DONE) {
    if (this.status === 200) {
      console.log(JSON.parse(this.responseText));
    } else {
      console.log(this.status, this.statusText);
    }
  }
};
xhr.send();

Is anybody here can answer this question who explain this issue for saving our time? Thank you!!


Solution

  • I believe axios GET headers require a data key to be specified, or else it will ignore the content-type (even though it is a GET request)

    So you can do something like this

    var config =    {
         data: {},
         headers : { 
            "Accept": "application/json",
            "Content-Type": "application/json",
         }
       };
    

    or

    var config =    {
         data: null,
         headers : { 
            "Accept": "application/json",
            "Content-Type": "application/json",
         }
       };