0

I'm trying to fetch data from a Node.JS API via Axios. The API only accepts requests with content-type "application/json" and GET HTTP Method. If the content-type is not "application/json", an error message will be sent back.

I've tested the API with Postman and other HTTP libraries and everything works perfectly fine.

However, when I try to make a request via Axios:

export const getPrivateInstance = axios.create({
    baseURL: API_URL,
    timeout: 25000,
    withCredentials: true
})

getPrivateInstance({
                method: 'get',
                url: "/getData",
                data: JSON.stringify({
                projectId: projectID
                }),
                headers: {
                     "Content-Type": 'application/json',
                }

})

the Content-Type is ignored when specifying GET as the HTTP Method. However, if I change the http method to POST in the axios config and API, it works. But with GET, the content-type is ignored by Axios.

How can one make a GET Request where the content-type is not ignored by Axios?

AmerllicA
  • 29,059
  • 15
  • 130
  • 154
thelearner
  • 1,440
  • 3
  • 27
  • 58
  • 3
    The content-type header describes the format of the request body. GET requests typically do not have a request body and therefore do not require a content-type header. Basically, the API is wrong in expecting / requiring any content-type header on GET requests – Phil Jun 09 '22 at 08:25
  • 1
    You also cannot send a request body with a GET request from the browser. They simply do not support it. XHR (which Axios uses) ignores it and `fetch()` will throw an error if you try – Phil Jun 09 '22 at 08:31
  • 1
    Is the API ElasticSearch? That's the only one I know of that tries to use GET request bodies but they also support POST requests because of limitations like this. – Phil Jun 09 '22 at 08:49
  • @Phil No, it's just a simple Node.JS Express API that I developed for learning purposes – thelearner Jun 09 '22 at 08:50
  • Oh, you should definitely change it then if you plan on supporting browser clients. There's some good reading to be had in [this post](https://stackoverflow.com/q/978061/283366) – Phil Jun 09 '22 at 08:51
  • @Phil you are sure that GET doesn't support content type? Mine is sending Content-Type JSON successfully with a GET request. (Not AXIOS) – Sunlight Oct 05 '22 at 09:52
  • @Sunlight I never said they don't support the header, I said they (browsers) don't support a request body with GET requests. And if you're not sending a body, there's absolutely no reason to set the header – Phil Oct 05 '22 at 13:26

0 Answers0