1

I have the following get request:

return axios
    .get<ArticlesResponse>(SUGGESTED_ARTICLES, {
      headers: {
        'Content-Type': 'application/json',
      },
    })
    .then(onRequestSuccess)
    .catch(onRequestError);

It returns me an object with the data I need, however, the data field inside the object is a string instead of an actual object. Anyone has any ideea about why? I looked it up and saw that adding that header above will fix the issue but it doesn't. Thanks in advance!

My onRequestSucces is:

export function onRequestSuccess<T = any>(response: AxiosResponse<T>) {
  console.log('Request Successful!', response);

  return response.data;
}

JSON.Parse() also won't fix it.

m.rp
  • 718
  • 8
  • 22
r00t -
  • 225
  • 1
  • 2
  • 12

2 Answers2

2

The problem may be due to the API returning a response that contains invalid JSON data, now JSON.parse would throw an error, but Axios manages the exception by setting the invalid JSON as string in the data property. Try using the Fetch API.

m.rp
  • 718
  • 8
  • 22
1

Since you're using a GET request (doesn't have a body) the 'Content-Type' is not being useful. This header is used to tell the server which type of content you're sending, but you're sending none. You should use it only on POST/PUT requests.

See this question for more details on this.

In order for your request to be read as JSON you have to set the header in the server. This will tell the browser you're receiving a JSON, which will then be parsed automatically by axios.

tibuurcio
  • 766
  • 8
  • 11