【问题标题】:VueJS and Laravel - post request always emptyVueJS 和 Laravel - 发布请求始终为空
【发布时间】:2017-07-10 06:52:02
【问题描述】:

我正在尝试使用 VueJS 2(带有 axios)和 Laravel 5.3 进行简单的 POST。当我尝试打印 $request->all() 时,我的方法总是返回一个空数组。

我的刀片模板中有以下元标记:

<meta name="csrf-token" content="{{ csrf_token() }}">

我正在加载 axios 并在 bootstrap.js 中添加 X-CSRF 标签:

window.Vue = require('vue');
window.axios = require('axios');

require('vue-axios');

window.axios.defaults.headers.common['X-CSRF-Token'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content')

这是我的 Vue 组件(为了清楚起见,缩小了范围):

<template>
    <div class="options">
        <div class="save-result" @click="saveResult()">
            Save result
        </div>
    </div>
</template>

<script>
    export default {
        methods: {
            saveResult: function() {
                axios.post('/api/user/save-results', {'test': 'testing'}).then(response => {
                    console.log(response.message)
                })
            }
        }
    }
</script>

这条路线通向一个非常简单的控制器,我只是打印我的请求,它是空的。

public function saveResults(Request $request)
{
    echo '<pre>'; print_r($request->all()) and die();
}

我猜我的 CSRF 标头设置缺少某些东西,但我不确定它可能是什么。

【问题讨论】:

  • 您是否检查了浏览器控制台中的网络选项卡以查看是否正在发送任何数据?
  • 原来问题是我发送了一个“常规”数组作为 axios 的 post 方法的第二个参数,它应该是一个对象。我将在下面发布答案。我不确定为什么没有隐式设置,知道为什么吗?

标签: vue.js laravel-5.3 vuejs2 csrf-protection axios


【解决方案1】:

原来问题是我发送一个数组作为 axios 的 post 方法的第二个参数,它应该是一个对象。

我利用了 ECMAScript 6 polyfill,Object.assign

let params = Object.assign({}, this.$store.getters.params)

axios.post('/api/user/save-results', params).then(response => {
     console.log(response.message)
})

【讨论】:

    猜你喜欢
    • 2016-10-18
    • 2015-12-24
    • 2021-08-11
    • 2018-03-22
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    相关资源
    最近更新 更多