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?
The XMLHttpRequest method send() sends the request to the server. If the request is asynchronous (which is the default), this method returns as soon as the request is sent and the result is delivered using events. If the request is synchronous, this method doesn't return until the response has arrived.
Yes, you can send a request body with GET but it should not have any meaning.
fetch() allows you to make network requests similar to XMLHttpRequest (XHR). The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API, avoiding callback hell and having to remember the complex API of XMLHttpRequest.
setRequestHeader('Content-Type', 'application/json') ; is added 1 line above or below the Accept header, the method used changes to OPTIONS, the Accept header changes to "text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8" and the Content-Type header disappears as if it wasn't seen.
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:...
- If the request method is
GET
orHEAD
, set body to null.
Also a request via the Fetch API does not allow a body. From the specification:
- If either init["body"] exists and is non-null or inputBody is non-null, and request’s method is
GET
orHEAD
, 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With