Ajax Post 到 Laravel - CSRF 令牌不匹配

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39539377/
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-09-14 14:28:08  来源:igfitidea点击:

Ajax Post to Laravel - CSRF Token Mismatch

javascriptphpjqueryajaxlaravel

提问by senty

I am trying to post data to Laravel backend with ajax, however I am getting 'CSRF token mismatch' error.

我正在尝试使用 ajax 将数据发布到 Laravel 后端,但是我收到“CSRF 令牌不匹配”错误。

First, I've placed token in html (in body but outside its form because it's not the whole form, its only 2 elements to be posted):

首先,我已经在 html 中放置了令牌(在正文中但在其表单之外,因为它不是整个表单,它只有 2 个要发布的元素):

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

Then in 'document ready', I try to post the data with ajax.

然后在“文档准备好”中,我尝试使用 ajax 发布数据。

data["_token"] = jQuery('#token').val();  

// Also tried this:
jQuery.ajaxSetup({
       headers: {
           'X-CSRF-TOKEN': jQuery('#token').val()
       }
})

console.log(data) // returns the array with _token: "esOKmY8Tpr4UvhTYMhWcWui0rpvYEjJ3es7ggics"

jQuery.ajax({
     type: "POST",
     url: '/my-route',
     data: data,
     success: function() {
          console.log("A");
     }
});

The data which I want to post are little chunk of a bigger form, and with using this approach, I can autocomplete form. The little chunk of html inputs are not inside any other sub-form. Maybe this can be the case?

我想发布的数据是更大表单的一小块,使用这种方法,我可以自动完成表单。一小块 html 输入不在任何其他子表单中。也许情况可能如此?

- Form:
- A: bla // to be posted
- B: hello  // to be posted
- C: smt else // no post

but getting the values are working okay

但获取值工作正常

Route:

路线:

Route::post('/my-route', 'AdminController@theFunction')->middleware('admin');

Route::post('/my-route', 'AdminController@theFunction')->middleware('admin');



Edit: I changed <input>to <meta>tag

编辑:我改变了<input><meta>标签

回答by Nour

I had the same problem try to put include CSRF tag in your metalike so

我遇到了同样的问题,尝试meta像这样将包含 CSRF 标签放入

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

and read it in your ajax code like so :

并在您的 ajax 代码中阅读它,如下所示:

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

Last Update

最后更新

Please modify your url variable like so :

请像这样修改您的 url 变量:

jQuery.ajax({
    type: "POST",
    url: '/my-route'+'?_token=' + '{{ csrf_token() }}',
    data: data,
    success: function() {
         console.log("A");
    }
  });

回答by Keshav Joshi

Try This

尝试这个

    var formData = new FormData();
    formData.append("_token", "{{ csrf_token() }}");
    $.ajax({
    headers: {
    'X-CSRF-TOKEN': "{{ csrf_token() }}"
    },
    url: 'save_search',
    data: formData,
    processData: false,
    type: 'POST',
    success: function ( data ) {
    alert( data );
    }
    });