来自浏览器的带有正文的异步 GET 请求 [英] async GET request with body from browser

查看:20
本文介绍了来自浏览器的带有正文的异步 GET 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

有什么办法吗?

解决方案

不,没有.

GET 请求不能有请求正文,你不能让他们拥有一个.GET 请求只检索数据,它们从不发送数据.

需要以空对象作为主体的 GET 请求的 API 不起作用.

显然,GET 请求允许有一个正文.大多数实现将忽略它或拒绝请求.但是即使提供你的 API 的服务器允许使用 body,你也不能使用它:

来自关于 XMLHttpRequest#send:

<块引用>

发起请求.可选参数提供请求实体正文.如果请求方法是 GET 或 HEAD,则忽略该参数. 如果状态不是 OPENED 或设置了 send() 标志,则抛出InvalidStateError"异常.

来自关于 Request 类的规范在获取 API 中:

<块引用>

如果 init 的 body 成员存在且为非空或 inputBody 为非空,并且 请求的方法为 GETHEAD然后抛出一个类型错误.

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

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?

解决方案

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.

这篇关于来自浏览器的带有正文的异步 GET 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆