使用公理发送对象获取请求

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

" N; "

我可以像这样使用 jQuery,它很有效:

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

该对象从服务器发送回来的幼虫如下:

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

同样的事情不适用于公理:

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

我使用 Axios 设置了一个默认的 baseURL,因此 URL 是不同的。它正确地到达 api 端点,函数返回发送进来的内容,显然不是对象。结果我只得到“ N;”。

225452 次浏览

Axios API is a bit different from the jQuery AJAX one. If you have to pass some params along with GET request, you need to use params property of config object (the second param of .get() method):

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

You can pass either a plain object or a URLSearchParams object as params value.

Note that here we're talking about params appended to URL (query params), which is explicitly mentioned in the documentation.

If you want to send something within request body with GET requests, params won't work - and neither will data, as it's only taken into account for PUT, POST, DELETE, and PATCH requests. There're several lengthy discussions about this feature, and here's the telling quote:

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.

Until it's fixed, the only option one has within a browser is to use POST/PUT requests when data just doesn't fit into that query string. Apparently, that option is only available if corresponding API can be modified.

However, the most prominent case of GET-with-body - ElasticSearch _search API - actually does support both GET and POST; the latter seems to be far less known fact than it should be. Here's the related SO discussion.