Send a GET request with a body in JavaScript (XMLHttpRequest)

Andrei Savin picture Andrei Savin · Feb 21, 2019 · Viewed 14.8k times · Source

I have to interact with an API that takes parameters from the body of a GET request. I know this might not be the best idea, but it is the way the API was built.

When I try building a query with XMLHttpRequest, it looks like the payload is simply not sent. You can run this and look in the network tab; the request is sent, but there is no body (tested in latest Chrome and Firefox):

const data = {
  foo: {
    bar: [1, 2, 3]
  }
}
const xhr = new XMLHttpRequest()
xhr.open('GET', 'https://my-json-server.typicode.com/typicode/demo/posts')
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
xhr.send(JSON.stringify(data))

Libraries such as axios are built on XMLHttpRequest, so they are not working either...

Is there any way to achieve this in JavaScript?

Answer

Ivar picture Ivar · Feb 21, 2019

No, it is not possible to send a GET request with a body in JavaScript.

it looks like the payload is simply not sent

That is correct. This is defined in the specification:

The send(body) method must run these steps:

...

  1. If the request method is GET or HEAD, set body to null.

Also a request via the Fetch API does not allow a body. From the specification:

  1. If either init["body"] exists and is non-null or inputBody is non-null, and request’s method is GET or HEAD, then throw a TypeError.

The best would be if the API could be fixed.

If that is not possible, you could add a server-side script that you can use as a proxy that passes the requests to the API. You can than call this script with a GET request with the data in the URL instead of the body or using a POST request with a body. This script then can make the GET request with a body (as long as the chosen language supports it).