2

Ok, I know it's a bad idea and it shouldn't be done but for the sake of this question please assume there's no other way - I am given API endpoint that requires GET request with empty object as a body.

Is there a way to do async request from browser? I'm using axios library which uses XMLHttpRequest under the hood and MDN says that send wipes the body when HTTP method is GET. I tried using native fetch but it gives me this error in browser: TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.

Is there any way to do it?

apieceofbart
  • 1,648
  • 1
  • 19
  • 25

1 Answers1

3

No, there isn't.

GET requests can't have a request body, you can't make them have one. GET requests only retrieve data, they never send data.

An API that requires GET request with empty object as a body just doesn't work.

Edit:

Apparently, GET requests are allowed to have a body. Most implementations will ignore it or reject the request. But even if the server that provides your API allows a body, you can't use it:

From the spec about XMLHttpRequest#send:

Initiates the request. The optional argument provides the request entity body. The argument is ignored if request method is GET or HEAD. Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set.

From the spec about the Request class in the fetch API:

If either init’s body member is present and is non-null or inputBody is non-null, and request’s method is GET or HEAD, then throw a TypeError.

That means that the answer to your question is still No.

PeterMader
  • 5,739
  • 1
  • 16
  • 27
  • 4
    hmmm when doing research I found that this is not *entirely* true - for example Elastic Search allows such case. So I believe this a grey area - standard doesn't directly forbids that. – apieceofbart Aug 07 '17 at 15:51
  • 1
    btw: this is the spec: https://tools.ietf.org/html/rfc7231#section-4.3.1 all it says is "A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request." – apieceofbart Aug 07 '17 at 15:53
  • 1
    Yes, it seems you're right. But I don't think `XMLHttpRequest` or the fetch API will let you give it a body. – PeterMader Aug 07 '17 at 16:11
  • 1
    Actually its not completely correct, GET request "can" have a request body which can be processed at the server end. – Golden_flash Apr 04 '19 at 15:14