来自浏览器的 body 的异步 GET 请求

async GET request with body from browser

好吧,我知道这是个坏主意,不应该这样做,但是为了这个问题,请假设没有其他方法 - 我得到了 API 端点,需要 GET 请求为空 object 作为 body.

有没有办法从浏览器进行异步请求? 我正在使用 axios 库,它在后台使用 XMLHttpRequestMDN 表示当 HTTP 方法为 GET 时,send 擦除 body。 我尝试使用本机 fetch 但它在浏览器中给我这个错误: TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.

有什么办法吗?

没有,没有。

GET requests 不能有请求体,你不能让他们有一个。 GET 请求仅检索数据,它们从不发送数据。

需要以空对象作为正文的 GET 请求的 API 是行不通的。

编辑:

显然,GET 请求允许有主体。大多数实现会忽略它或拒绝请求。但是即使提供你的 API 的服务器允许 body,你也不能使用它:

来自关于 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.

来自关于 Request class 的规范 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.

这意味着你的问题的答案仍然是