我想发送一个带有对象的获取请求。对象数据将在服务器上用于更新 session 数据。但是对象似乎没有被正确发送,因为如果我尝试将它发送回去打印出来,我只会得到:
"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 端点并且该函数返回发送的内容,这显然不是对象。结果我只得到“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 .