使用 axios get 请求发送对象

Send object with axios get request

我想发送带有对象的获取请求。对象数据将在服务器上用于更新会话数据。但是对象似乎没有被正确发送,因为如果我尝试将它发送回去打印出来,我只会得到:

" N; "

我可以像这样用 jQuery 来做并且它有效:

 $.get('/mysite/public/api/updatecart', { 'product': this.product },  data => {     
              console.log(data);
           });

对象从服务器发回 laravel 像这样:

public function updateCart(Request $request){
      return serialize($request->product);

同样的事情不适用于 axios:

axios.get('/api/updatecart', { 'product': this.product })       
                .then(response => {
                    console.log(response.data);
            });

我用 axios 设置了一个默认的 baseURL,所以 url 是不同的。它正确地到达了 api 端点并且函数 returns 发送了什么,这显然不是对象。结果我只得到“N;”。

Axios API 与 jQuery AJAX 有点不同。如果必须在 GET 请求中传递一些参数,则需要使用 config 对象的 params 属性(.get() 方法的第二个参数):

axios.get('/api/updatecart', {
  params: {
    product: this.product
  }
}).then(...)

您可以传递普通对象或 URLSearchParams 对象作为 params 值。

请注意,这里我们讨论的是附加到 URL(查询参数)的参数,这在文档中有明确提及。

如果您想使用 GET 请求在请求 body 中发送某些内容,params 将不起作用 - data 也不会,因为它只是考虑到 PUT、POST、DELETE 和 PATCH 请求。有 several lengthy discussions 关于此功能,这里是引述:

Unfortunately, this doesn't seem to be an axios problem. The problem seems to lie on the http client implementation in the browser javascript engine.

According to the documentation and the spec XMLHttpRequest ignores the body of the request in case the method is GET. If you perform a request in Chrome/Electron with XMLHttpRequest and you try to put a json body in the send method this just gets ignored.

Using fetch which is the modern replacement for XMLHtppRequest also seems to fail in Chrome/Electron.

在修复之前,浏览器中唯一的选择是在数据不适合该查询字符串时使用 POST/PUT 请求。显然,该选项只有在相应的 API 可以修改时才可用。

然而,GET-with-body 最突出的案例 - ElasticSearch _search API - 实际上支持 GET 和 POST;后者似乎远没有应有的那样广为人知。这是 related SO discussion.