1

请注意,我使用的是 Laravel 框架。另请注意,SO上有类似的问题,我已经检查过了,但无法根据这些解决方案解决我的问题......

即使我根据我的知识设置了我的 CSRF 令牌,但我不确定它为什么不起作用。

检查控制台时,我似乎有 3 个 cookie:两个 Request cookie,其中一个被调用XSRF-TOKEN,一个被调用laravel_session。和一个响应laravel_session饼干。都有不同的价值!!!

我的 Vue:

new Vue({
    el:'body',
    http: {
        root: '/root',
        headers: {
            'X-CSRF-Token': $('meta[name=_token]').attr('content')
        }
    },  
});

我的头:

<meta name="_token" content="{!! csrf_token() !!}"/>

我的 Vue 组件 addNew 方法:

Vue.component('things',{
    template:'#things-panel-template',
    data(){
        return {
            list: [],
            newThing: {
                body: '',
                // _token: $('meta[name=_token]').attr('content'),
                // tried removing token from head meta and adding up here.
            },
        }
    },
    methods:{
        addNew(){
            var thing = this.newThing; // get input
            this.newThing = {body:''}; // clear input
            this.$http.post('/api/things/add',thing) // send
        },
    },
});

我的路线:

Route::post('/api/things/add',function(){
    return App\Thing::create(Request::get());
});

最后,我的 Vue 模板中的表单:

<form action="/things/add"
        method="POST"
        @submit.prevent="addNew"
    >
        <div class="form-group">
            {{ csrf_field() }}
            <label for="">Add</label>
            <input type="text"
                name="body"
                id="task-body"
                class="form-control"
                v-model="newThing.body"
            >
            <button :disabled="!isValid"
                class="btn btn-primary"
                type="submit"
            >Add</button>
        </div>
    </form>
4

2 回答 2

2

尝试这个:

this.$parent.$http.post('/api/things/add', thing)

代替

this.$http.post('/api/things/add', thing)

或者使用全局配置设置默认值:

Vue.http.headers.common['X-CSRF-TOKEN'] = $('meta[name=_token]').attr('content');
于 2016-07-12T19:33:45.157 回答
1

我自己找到了答案:

如果您要使用 vue 组件,则应该将令牌添加到该组件中。否则它不会与您的 ajax 请求一起使用。所以把这部分放在组件中的模板下面:

    http: {
        root: '/root',
        headers: {
            'X-CSRF-Token': $('meta[name=_token]').attr('content')
        }
    },  

执行此操作以检查您的令牌是否在标头内正确发送:

  1. 转到谷歌浏览器,打开开发工具,转到网络选项卡并重新加载。
  2. 进行 ajax 调用并查看在网络选项卡中添加的文件,打开它并转到“标题”选项卡。
  3. 查看底部显示的位置:“请求标头”并检查令牌是否已正确添加到请求中。
于 2016-07-14T13:39:47.627 回答