如何通过 Ajax in Laravel 5.2 的 CSRF 保护

How to get through CSRF Protection with Ajax in Laravel 5.2

我想发送 Ajax post 请求,但我遇到了一些 CSRF 问题。

这是我的 js 代码:

 function sendAjaxRequest(index){
    var token = $('meta[name=csrf_token]').attr('content')
    $.ajaxSetup({ headers: { 'csrftoken' : token } });
    $.ajax({
       method: "POST",
        data: '{"value":"10"}', 
       dataType: 'json',
       url: "http://localhost/laravel/public/",
    });
 }

这是我的 laravel routes.php 文件中的路线:

Route::post('/','AjaxController@updateOrder');

这是我的控制台(jQuery 问题):

POST http://localhost/kaemo/public/ 500 (Internal Server Error)

这是我的网络预览:

TokenMismatchException in VerifyCsrfToken.php line 67:

有什么想法吗?

尝试将令牌放入您的 data

var token = "{{csrf_token()}}";
$.ajax({
   method: "POST",
    data: '{"value":"10", _token: token}', 
   dataType: 'json',
   url: "http://localhost/laravel/public/",
});

尝试在 X-CSRF-TOKEN 中设置 CSRF 令牌,例如,

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

并在您的 app/Http/Middleware/VerifyCsrfToken.php 中添加以下代码,向其中添加 tokenMatch() 方法。

<?php
    /**
     * Determine if the session and input CSRF tokens match.
     *
     * @param \Illuminate\Http\Request $request
     * @return bool
     */
    protected function tokensMatch($request)
    {
        // If request is an ajax request, then check to see if token matches token provider in
        // the header. This way, we can use CSRF protection in ajax requests also.
        $token = $request->ajax() ? $request->header('X-CSRF-Token') : $request->input('_token');

        return $request->session()->token() == $token;
    }

阅读更多[Laravel5] TokenMismatchException in VerifyCsrfToken