I want to send a get request with an object. The object data will be used on the server to update session data. But the object doesn't seem to be sent correctly, because if I try to send it back to print it out, I just get:
" N; "
I can do it with jQuery like this and it works:
$.get('/mysite/public/api/updatecart', { 'product': this.product }, data => {
console.log(data);
});
The object is sent back from server with laravel like this:
public function updateCart(Request $request){
return serialize($request->product);
The same thing doesn't work with axios:
axios.get('/api/updatecart', { 'product': this.product })
.then(response => {
console.log(response.data);
});
I set a default baseURL with axios so the url is different. It reaches the api endpoint correctly and the function returns what was sent in, which was apparently not the object. I only get "N; " as result.
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.