来自浏览器的主体与GET异步请求

来自浏览器的主体与GET异步请求

本文介绍了来自浏览器的主体与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并且 MDN 表示,当HTTP方法为GET时,send会擦除主体.我尝试使用本机fetch,但是在浏览器中却给了我这个错误:TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have 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.

有什么办法吗?

推荐答案

不,没有.

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 :

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

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

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

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

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

08-01 05:50