繁体   English   中英

ajax请求中的laravel TokenMismatchException

[英]laravel TokenMismatchException in ajax request

我正在使用资源组并使用此过滤器来解决TokenMismatchException问题:

Route::filter('csrf', function($route, $request) {
    if (strtoupper($request -> getMethod()) === 'GET') {
        return;
        // get requests are not CSRF protected
    }

    $token = $request -> ajax() ? $request -> header('X-CSRF-Token') : Input::get('_token');

    if (Session::token() != $token) {
        throw new Illuminate\Session\TokenMismatchException;
    }
});

我的路线:

Route::group(array('prefix'=> 'admin', 'before' => 'csrf'), function(){
    Route::resource('profile' , 'ProfileController', array('as'=>'profile') );
});

现在。 我收到Ajax请求的错误,例如这段代码:

<script type="text/javascript">
    $(document).ready(function() {
       $('#frm').submit(function(e){
           e.preventDefault();
           name         = $('#name').val();
           family       = $('#family').val();
           email        = $('#email').val();
           currPassword = $('#currPassword').val();
           password     = $('#password').val();
           password_confirmation = $('#password_confirmation').val();     

           $.post("{{ route('admin.profile.update', $profile->id) }}",
                { 
                  _method : 'PUT',
                  name                  : name,
                  family                : family,
                  email                 : email,
                  currPassword          : currPassword,
                  password              : password,
                  password_confirmation : password_confirmation  
                },
                function(data)
                {
                    alert(data.errors.name);
                },'json');
                return false;
       });
});
</script>

错误:

{"error":{"type":"Illuminate\\Session\\TokenMismatchException","message":"","file":"\/var\/www\/alachiq\/app\/filters.php","line":83}}

我想我必须在$.post发送_token。 但我无法获得带有name属性的input标记。 我发现这个错误:

TypeError: 'stepUp' called on an object that does not implement interface HTMLInputElement.

Laravel文档中提供了有关如何执行此操作的提示。 这可能在提出问题时尚未提供,但我想我会用答案更新它。

http://laravel.com/docs/master/routing#csrf-x-csrf-token

我已经从文档中测试了元标记方法并使其正常工作。 将以下元标记添加到全局模板中

<meta name="csrf-token" content="{{ csrf_token() }}">

添加此JavaScript,为jQuery中的所有ajax请求设置默认值。 最好是在您的应用中包含的js文件中。

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

此令牌可以存在于请求标头或表单中。 这会将其填充到每个ajax请求的请求标头中。

您必须使用_token插入隐藏的输入,然后获取该值以获取ajax帖子中的其他表单字段。

<input type="hidden" name="_token" value="{{ csrf_token() }}" />

另一种方法,

在您的视图中,您可以使用_token设置对象

<script type="text/javascript">
    var _globalObj = {{ json_encode(array('_token'=> csrf_token())) }}
</script>

然后在你的ajax调用中,你可以从对象中获取_token,如下所示:

var token = _globalObj._token;

并将其包含在您的ajax帖子中。

就像我在下面的代码中所示,做简单的事情,

    $.ajax({
        type: 'POST',
        url: 'your-post-route-url',
        data: {
            "_token": "{{ csrf_token() }}",
            "form_data": $('#Form').serialize(),
        },
        success: function (data) {
            console.log(data);
        },
        error: function (reject) {
            console.log(reject);
        }
    });

我希望这是一个解决这个问题的最简单的方法,没有任何隐藏的领域,它在laravel 5.4版本中适用于我:)

希望能帮助到你。

你也可以添加在你的VerifyCsrfToken.php文件中给你错误的VerifyCsrfToken.php

protected $except = [
    //
]

假设您的路线已发布。 你可以像这样添加

protected $except = ['post',
    //
];`... 

希望这有助于其他人。

  <html>
  <head>
  <title>Ajax Example</title>
      <meta name="csrf-token" content="<?php echo csrf_token() ?>" />    
  <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
  </script>

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

  <script>
     function getMessage(){
        $.ajax({
           type:'POST',
           url:'/getmsg',
           data:'_token = <?php echo csrf_token() ?>',
           data:'',
           success:function(data){
              $("#msg").html(data.msg);
           }
        });
     }
  </script>
  </head>

  <body>


  <div id = 'msg'>This message will be replaced using Ajax. 
     Click the button to replace the message.</div>
  <?php
     echo Form::button('Replace Message',['onClick'=>'getMessage()']);
  ?>
  </br>


  </body>

  </html>

VerifyCsrfToken.php文件添加此功能

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM