laravel 使用 axios get 请求发送对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46404051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:49:59  来源:igfitidea点击:

Send object with axios get request

laravelvue.jsaxios

提问by Galivan

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; "

" N; "

I can do it with jQuery like this and it works:

我可以像这样用 jQuery 来做到这一点,它的工作原理:

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

The object is sent back from server with laravel like this:

对象从服务器用 laravel 发回,如下所示:

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

The same thing doesn't work with axios:

同样的事情不适用于 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 设置了一个默认的 baseURL,所以 url 是不同的。它正确到达 api 端点,函数返回发送的内容,这显然不是对象。结果我只得到“ N;”。

回答by raina77ow

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

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

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