How to pass laravel CSRF token value to vue

后端 未结 6 668
滥情空心
滥情空心 2020-12-02 22:57

I have this form where the user should only type text inside a text area:

            
{{-- Name of the me
6条回答
  •  春和景丽
    2020-12-02 23:32

    I solved it thanks to these two answers:

    1) First I read this one, which led me to

    2) This second one.

    So, in my form I keep this:

    {{ csrf_field() }}

    And inside the js file I only add the following (outside and above the Vue instance):

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

    So the whole js code is:

    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,
                        }
                    });
                }
            },
        });
    

提交回复
热议问题