Send a GET request with a body in JavaScript (XMLHttpRequest) [duplicate]

房东的猫 提交于 2020-08-04 03:54:52

问题


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?


回答1:


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).



来源:https://stackoverflow.com/questions/54810942/send-a-get-request-with-a-body-in-javascript-xmlhttprequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!