Getting Error: CSRF token mismatch in laravel 8

Getting Error: CSRF token mismatch in laravel 8

我正在尝试使用 ajax 在 laravel 中提交表单,其中包含一些输入类型和上传文件选项。提交表单后,出现错误 -

{message: "CSRF token mismatch.", exception: "Symfony\Component\HttpKernel\Exception\HttpException",…}exception: "Symfony\Component\HttpKernel\Exception\HttpException"file: "D:\development\laravel\parangatcrm\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php"line: 389message: "CSRF token mismatch."

I have added this in my blade file -
 <meta name="csrf-token" content="{{ csrf_token() }}"> 
<input type="hidden" name="csrf-token" value="{{ csrf_token() }}">

This is my ajax code - 
$.ajax({
                    url: url,
                    type: 'PATCH',
                    data: new FormData($("#formId")[0]),
                    cache : false,
                    processData: false,
                    contentType: false,
                    success: function (res){
                        console.log(res);
                    }
                    ,error: function (err){
                        console.log(err);
                    }
                });

您需要在 header 上发送 csrf 令牌,而不是与表单数据一起发送。在你的代码上尝试这样的事情:

要为每个请求添加默认 header,请使用 $.ajaxSetup():

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

否则您可以像下面的代码一样添加 header:

$.ajax({
                        url: url,
                        headers: { 'X-CSRF-Token': ('meta[name="csrf-token"]').attr('content') }
                        type: 'PATCH',
                        data: new FormData($("#formId")[0]),
                        cache : false,
                        processData: false,
                        contentType: false,
                        success: function (res){
                            console.log(res);
                        }
                        ,error: function (err){
                            console.log(err);
                        }
                    });