php ajax请求中的laravel TokenMismatchException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21627170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:18:04  来源:igfitidea点击:

laravel TokenMismatchException in ajax request

phpajaxlaravellaravel-4

提问by DolDurma

i'm using resource group and use this filter to resolve TokenMismatchExceptionproblem:

我正在使用资源组并使用此过滤器来解决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;
    }
});

my route :

我的路线:

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

now. i get error to Ajax requests such as this code:

现在。我收到错误 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:

错误:

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

i think i'm must be sent _token in $.post. but i can not get inputtag with nameattribute. iget this error:

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

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

回答by Paul Zepernick

There is a tip in the Laravel docs on how to do this. This might not have been available at the time of the question, but I thought I would update it with a answer.

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

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

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

I have tested the meta tag method from the documentation and got it working. Add the following meta tag into your global template

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

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

Add this JavaScript that sets defaults for all ajax request in jQuery. Preferably in a js file that is included across your app.

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

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

This token can exist in the request header or the form. This populates it into the request header of every ajax request.

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

回答by Philip

You have to insert a hidden input with the _token and later get that value as you do to get the other form fields in your ajax post.

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

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

An another method,

另一种方法,

On your view you can set an object with the _token

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

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

and later on your ajax call you can get the _token from the object like this:

稍后在您的 ajax 调用中,您可以像这样从对象中获取 _token:

var token = _globalObj._token;

and include it on your ajax post.

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

回答by Sagar Naliyapara

Just do simple thing as i have shown in following code,

就像我在以下代码中显示的那样做简单的事情,

    $.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);
        }
    });

I hope this one is the easiest way to solve this problem without any hidden field and it works for me in laravel 5.4 version :)

我希望这是在没有任何隐藏字段的情况下解决这个问题的最简单方法,它在 laravel 5.4 版本中对我有用:)

Hope it helps.

希望能帮助到你。

回答by emeval21

You can as well add the url thats giving you the error inside the VerifyCsrfToken.phpfile in the

您还可以添加在VerifyCsrfToken.php文件中给您错误的网址

protected $except = [
    //
]

Let's say your route is post. You can just add in like this

假设您的路线是邮寄。你可以像这样添加

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

Hope this helps others.

希望这对其他人有帮助。

回答by FunZall Crazy

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

and VerifyCsrfToken.phpfile add this function

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