来自浏览器的主体与GET异步请求 [英] async GET request with body from browser

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

问题描述

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

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.

是否可以通过浏览器执行异步请求? 我正在使用axios库,该库在内部使用了XMLHttpRequest并且

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.

有什么办法吗?

推荐答案

不,没有.

GET请求不能具有请求正文,您不能使它们具有一个. GET请求仅检索数据,而从不发送数据.

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

需要以空对象作为主体的GET请求的API不能正常工作.

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

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

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:

根据有关 XMLHttpRequest#send :

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

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.

根据关于fetch API中 Request的规范:

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

如果任何一个init的body成员存在并且为非null或 inputBody为非null ,并且 request的方法为GETHEAD ,则然后引发TypeError .

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

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

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

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