Search code examples
javascriptangularjslaravel-5csrf-protection

How to get and send _token from an html page when submitting a form request to laravel 5 app


I have an app with the client side written in HTML and Angularjs and the server-side in Laravel 5. Each time I submit my form, I send the models using $http to a route in my laravel 5 app but I keep having the error

production.ERROR: exception 'Illuminate\Session\TokenMismatchException'...

I know it is because _token is absent among my models. But how do I get it since my form page is purely in HTML and Javascript. Thanks


Solution

  • This is quite common problem. You need to use tag and add the header X-CSRF-TOKEN like this

    <meta name="csrf-token" content="{{ csrf_token() }}" />
    
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    

    More info at http://laravel.com/docs/master/routing#csrf-protection