hemal's avatar
Level 1

How can I use CSRF token with axios post method?

Im new to vue in laravel. earlier when I want to save some data throw an action below form I can use {{ csrf_field() }}

How can I do that when using axios.post,

In my console it will give a error

CSRF token not found:

I know because I didnt defined that can someone tell me how to do that

my app.js file like below


require('./bootstrap');

window.Vue = require('vue');
var Vue = require('vue');
Vue.use(require('vue-resource'));

Vue.component('example', require('./components/Example.vue'));

const app = new Vue({
    el: '#new',

    data: {
        message: 'Update New Post:',
        content: '',
    },

    methods:{

        addPost(){
            axios.post('/addPost', {
              content: this.content
            })
            .then(function(response) {
              console.log(response);
            })
            .catch(function(error) {
              console.log(error);
            });
        }
    }
});

and my home.blade file like below


    <div id="new">
          <form class="form-horizontal" role="form" enctype="multipart/form-data" method="POST" v-on:submit.prevent="addPost">
          {{ csrf_field() }}
            <h4>@{{message}}</h4>
            <div class="form-group" style="padding:14px;">
              <textarea v-model="content" class="form-control" placeholder="Update your status"></textarea><br>
              <button class="btn btn-primary pull-right" type="submit">Post</button>
            </div>
          </form>
        </div>

data will added to database but it gives an error like csrf token not found

1 like
4 replies
tisuchi's avatar

Inside your html head, add like this-

<html>
    <head>
        <script>
        // rename myToken as you like
        window.myToken =  <?php echo json_encode([
            'csrfToken' => csrf_token(),
        ]); ?>
        </script>
    </head>

Now in your vue, just get token value.

For instance-

console.log(myToken.csrfToken);

Alternative way

You can achieve this in many ways. You can try this also- https://laravel.com/docs/5.2/routing#csrf-x-csrf-token

1 like
abusalameh's avatar

you need first to require axios then append the headers


window.axios = require('axios');

window.axios.defaults.headers.common = {
    'X-Requested-With': 'XMLHttpRequest',
    'X-CSRF-TOKEN' : document.querySelector('meta[name="csrf-token"]').getAttribute('content');
};



12 likes
Chris_Ruskai's avatar

I have this set up the way @abusalameh has it. In my Vue app, when a user clicks a "like" button, it sends an HTTP post to the server to "like" the article. This works for the first post, but if I click it again, I get a CSRF error from Laravel. Does anyone know how to persist this?

EDIT: I discovered that this is actually an issue with my session when working locally. Fixing the issue solved my problem.

Please or to participate in this conversation.