且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用JavaScript(XMLHttpRequest)发送带有正文的GET请求

更新时间:2022-03-19 05:17:53

否,无法使用JavaScript发送带有正文的GET请求.

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:

send(body)方法必须运行以下步骤:

The send(body) method must run these steps:

...

  1. 如果请求方法是GETHEAD,请将 body 设置为null.
  1. If the request method is GET or HEAD, set body to null.

另外,通过获取API 的请求不允许身体.来自规范:

Also a request via the Fetch API does not allow a body. From the specification:

  1. 如果init ["body"]存在且为非null或inputBody为非null,并且请求的方法为GETHEAD,则抛出TypeError.
  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.

***是可以修复该API.

The best would be if the API could be fixed.

如果无法实现,则可以添加服务器端脚本,将其用作将请求传递到API的代理.然后,您可以使用带有URL中数据而不是正文的GET请求或带有正文的POST请求来调用此脚本.然后,该脚本可以使用主体发出GET请求(只要所选语言支持该请求即可).

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