使用JavaScript(XMLHttpRequest)发送带有正文的GET请求 [英] Send a GET request with a body in JavaScript (XMLHttpRequest)

查看:550
本文介绍了使用JavaScript(XMLHttpRequest)发送带有正文的GET请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须与从GET请求的主体获取参数的API进行交互.我知道这可能不是最好的主意,但这是API的构建方式.

I have to interact with an API that takes parameters from the body of a GET request. I know this might not be the best idea, but it is the way the API was built.

当我尝试使用XMLHttpRequest构建查询时,看起来好像根本没有发送有效负载.您可以运行此程序,然后在网络"标签中查看;请求已发送,但没有正文(在最新的Chrome和Firefox中经过测试):

When I try building a query with XMLHttpRequest, it looks like the payload is simply not sent. You can run this and look in the network tab; the request is sent, but there is no body (tested in latest Chrome and Firefox):

const data = {
  foo: {
    bar: [1, 2, 3]
  }
}
const xhr = new XMLHttpRequest()
xhr.open('GET', 'https://my-json-server.typicode.com/typicode/demo/posts')
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
xhr.send(JSON.stringify(data))

axios之类的库基于XMLHttpRequest构建,因此它们也不起作用...

Libraries such as axios are built on XMLHttpRequest, so they are not working either...

有什么方法可以用JavaScript来实现吗?

Is there any way to achieve this in JavaScript?

推荐答案

否,无法使用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).

这篇关于使用JavaScript(XMLHttpRequest)发送带有正文的GET请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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