如何将laravel CSRF令牌值传递给vue

Pat*_*ros 23 laravel vue.js laravel-5.3

我有这种形式,用户只应在文本区域内键入文本:

            <form action="#" v-on:submit="postStatus">{{-- Name of the method in Vue.js --}}
                <div class="form-group">
                    <textarea class="form-control" rows="5" maxlength="140" autofocus placeholder="What are you upto?" required v-model="post"></textarea>
                </div>
                <input type="submit" value="Post" class="form-control btn btn-info">

                {{ csrf_field() }}

            </form>
Run Code Online (Sandbox Code Playgroud)

然后,我有这个脚本代码,我将vue.js与ajax一起使用,以便将该文本传递给控制器​​并最终将其保存到数据库中:

//when we actually submit the form, we want to catch the action
    new Vue({
        el      : '#timeline',
        data    :   {
            post    : '',
        },
        http    :   {
            headers: {
                'X-CSRF-Token': $('meta[name=_token]').attr('content')
            }
        },
        methods : {
            postStatus : function (e) {
                e.preventDefault();
                console.log('Posted: '+this.post+ '. Token: '+this.token);
                $.ajax({
                    url         :   '/posts',
                    type        :   'post',
                    dataType    :   'json',
                    data        :   {
                        'body'  :   this.post,
                    }
                });
            }
        },
    });
Run Code Online (Sandbox Code Playgroud)

但是,到目前为止,这不起作用,因为存在此令牌不匹配异常.我不知道如何让它发挥作用.如何将此标记值传递给控制器​​.我尝试过以下方法:

1)在表单内部,我为令牌添加了一个vue名称:

<input type="hidden" name="_token" value="YzXAnwBñC7qPK9kg7MGGIUzznEOCi2dTnG9h9çpB" v-model="token">
Run Code Online (Sandbox Code Playgroud)

2)我试图将此标记值传递给vue:

//when we actually submit the form, we want to catch the action
    new Vue({
        el      : '#timeline',
        data    :   {
            post    : '',
            token   : '',
        },
        methods : {
            postStatus : function (e) {
                e.preventDefault();
                console.log('Posted: '+this.post+ '. Token: '+this.token);
                $.ajax({
                    url         :   '/posts',
                    type        :   'post',
                    dataType    :   'json',
                    data        :   {
                        'body'  :   this.post,
                        '_token':   this.token,
                    }
                });
            }
        },
    });
Run Code Online (Sandbox Code Playgroud)

...但在控制台中,vue甚至没有抓住它:(

这导致我出现以下错误:

VerifyCsrfToken.php第68行中的TokenMismatchException:

我如何解决它?有任何想法吗?

Md.*_*hid 24

Very Easy Solution 只需在表单中添加隐藏字段即可.一个例子

<form id="logout-form" action="/logout" method="POST" style="display: none;">
    <input type="hidden" name="_token" :value="csrf">
</form>
Run Code Online (Sandbox Code Playgroud)

现在在vue文件中添加csrf变量内部脚本,就像这样.(请记住,它必须是内部数据).

<script>
     export default {
        data: () => ({
            csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
          }),        
    }
</script>
Run Code Online (Sandbox Code Playgroud)

注意您将在blade.php文件中看到这样的元标记.

<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
Run Code Online (Sandbox Code Playgroud)

如果没有这样的东西,你需要把它放在那里.

  • 如果您一开始就没有从 Laravel 提供任何 HTML,那么这将不起作用。 (3认同)

小智 5

更好的方法是简单地通过插槽将csrf令牌传递到vue组件中。

在blade.php文件中:

@extends('layouts.app')

@section('content')
          <my-vue-component>
            {{ csrf_field() }}
          </my-vue-component>
@endsection
Run Code Online (Sandbox Code Playgroud)

在MyVueComponent.vue中

   <form role="form">
       <slot>
         <!-- CSRF gets injected into this slot -->
       </slot> 
       <!-- form fields here -->
    </form>
Run Code Online (Sandbox Code Playgroud)

  • 如果您一开始就没有从 Laravel 提供任何 HTML,那么这将不起作用。 (3认同)

Pat*_*ros 3

我通过这两个答案解决了这个问题:

1)首先我读了这篇文章,这让我

2)第二个

所以,在我的表格中我保留了这个:

{{ csrf_field() }}

在 js 文件内,我只添加以下内容(Vue 实例的外部和上方):

var csrf_token = $('meta[name="csrf-token"]').attr('content');

所以整个js代码是:

var csrf_token = $('meta[name="csrf-token"]').attr('content');
    /*Event handling within vue*/
    //when we actually submit the form, we want to catch the action
    new Vue({
        el      : '#timeline',
        data    :   {
            post    : '',
            token   : csrf_token,
        },
        methods : {
            postStatus : function (e) {
                e.preventDefault();
                console.log('Posted: '+this.post+ '. Token: '+this.token);
                $.ajax({
                    url         :   '/posts',
                    type        :   'post',
                    dataType    :   'json',
                    data        :   {
                        'body'  :   this.post,
                        '_token':   this.token,
                    }
                });
            }
        },
    });
Run Code Online (Sandbox Code Playgroud)