laravel - 使用 axios get 请求发送对象

标签 laravel vue.js axios

<分区>

我想发送一个带有对象的获取请求。对象数据将在服务器上用于更新 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 .

关于laravel - 使用 axios get 请求发送对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46404051/

相关文章:

javascript - 为什么我的组件在将数据发布到 REST 服务后不更新

mysql - 如何在 laravel 5.3 中将 group by 添加到 hasMany 关系中?

php - 未定义数量的有效负载参数 - RESTful

vue.js - 在vue-nativescript上无法使vue-devtools独立应用程序正常工作

javascript - 如何正确使用 v-if 和 v-for 嵌套对象 vue js

node.js - 尝试创建 Vue 应用程序,但在终端中运行命令时获取 "SyntaxError: Unexpected identifier"

node.js - 通过 axios 设置 Redux 存储的默认状态

javascript - react 状态未正确显示

laravel - php artisan serve 命令有效,但 url 无效

php - Laravel 过滤所有列中的值