添加带有表单数据的 laravel CSRF 令牌

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

Adding laravel CSRF token with form data

javascriptphplaravellaravel-5laravel-5.3

提问by rakibtg

While uploading an image via wysiwyg editor I need to pass the Laravel CSRF token with the FormData(). But it seems like it fails or it does not add the csrf token using the append()method.

通过所见即所得编辑器上传图像时,我需要将 Laravel CSRF 令牌与FormData(). 但它似乎失败了,或者它没有使用该append()方法添加 csrf 令牌。

Here is my code:

这是我的代码:

  function uploadImage( image ) {
    var data = new FormData();
    data.append( "image", image );

    data.append( "csrfToken", Laravel.csrfToken ); // <- adding csrf token
    // Laravel.csrfToken will return the csrf token.

    console.log( data.entries() );
    $.ajax ({
      data: data,
      type: "POST",
      url: "/article/store/image",
      cache: false,
      contentType: false,
      processData: false,
      success: function(url) {
        var image = IMAGE_PATH + url;
          $( '#editor' ).summernote( "insertImage", image );
        },
        error: function( data ) {
          console.log( data );
        }
    });
  }

enter image description here

在此处输入图片说明

Its not adding the laravel csrf token with the form data because still I am getting an error

它没有在表单数据中添加 laravel csrf 令牌,因为我仍然收到错误

TokenMismatchException in VerifyCsrfToken.php line 68

VerifyCsrfToken.php 第 68 行中的 TokenMismatchException

How to add the token with the form data?

如何在表单数据中添加令牌?

回答by Saumya Rastogi

You should add a field named - _token, instead of csrfTokenlike this:

您应该添加一个名为 - 的字段_token,而不是csrfToken这样:

data.append( "_token", Laravel.csrfToken ); // <- adding csrf token

This is what Laravel's helper method - csrf_field()does.

这就是 Laravel 的辅助方法 -csrf_field()所做的。

According to Laravel Docs, in case of Ajax calls - you could, for example, store the token in a HTML meta tag::

根据Laravel Docs,在 Ajax 调用的情况下 - 例如,您可以将令牌存储在 HTML 元标记中:

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

and then include in your ajax header like this:

然后像这样包含在你的 ajax 标头中:

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

Hope this helps!

希望这可以帮助!

回答by jcorry

For ajax requests, I like to set it up once with $.ajaxSetup.

对于ajax请求,我喜欢用$.ajaxSetup设置一次。

In my layout:

在我的布局中:

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

In my app.js:

在我的 app.js 中:

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

This saves me having to remember to append the _token input to every request.

这使我不必记住将 _token 输入附加到每个请求。

回答by Rahul Ravindran

while @Saumya already answered this question, I use headers to send CSRF tokens like so:

虽然@Saumya 已经回答了这个问题,但我使用标头发送 CSRF 令牌,如下所示:

$.ajax ({
  data: data,
  type: "POST",
  headers: {'X-CSRF-TOKEN': Laravel.csrfToken },
  url: "/article/store/image",
  cache: false,
  contentType: false,
  processData: false,
  success: function(url) {
    var image = IMAGE_PATH + url;
      $( '#editor' ).summernote( "insertImage", image );
    },
    error: function( data ) {
      console.log( data );
    }
});  

If you are using ajax to send multiple requests throughout your application, you can set it up globally for every request at once:

如果您使用 ajax 在整个应用程序中发送多个请求,您可以一次为每个请求全局设置它:

$.ajaxSetup({
headers: {
    'X-CSRF-TOKEN': Laravel.csrfToken
}
});

Learn more Here

在这里了解更多