drkrsx3135168 2016-08-23 07:45
浏览 83
已采纳

如何在Laravel 5.2中使用Ajax进行CSRF保护

I want to send a Ajax post request but i get some issues with CSRF.

Here is my js code :

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

Here is my route from my laravel routes.php file :

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

Here is my console (jQuery issue) :

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

Here is my network preview :

TokenMismatchException in VerifyCsrfToken.php line 67:

Any ideas ?

  • 写回答

2条回答 默认 最新

  • dongli8862 2016-08-23 08:01
    关注

    Try to set CSRF token in X-CSRF-TOKEN like,

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

    And add the below code in your app/Http/Middleware/VerifyCsrfToken.php, add the tokenMatch() method to this.

    <?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;
        }
    

    Read more [Laravel5] TokenMismatchException in VerifyCsrfToken

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题