簡體   English   中英

Laravel 5.8 提交時顯示 CSRF 令牌不匹配 ajax POST

[英]Laravel 5.8 show CSRF token mismatch when submit ajax POST

  1. 我在 header 視圖中添加了代碼,如下所示
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
  1. 我的 ajax 代碼如下
$.ajaxSetup({
          headers:
          {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
 });
 $.ajax({
          method: "POST",
          url: "{{ route('ProgresOps.store') }}",
          data: form_data,contentType: false,       // The content type used when sending data to the server.
          cache: false,             // To unable request pages to be cached
          processData: false,
        })
        .done(function(data){
          toastr.success('Data saved.');
});

但是當我提交數據時結果是csrf mismatch,我還沒有找到解決方案

exception: "Symfony\Component\HttpKernel\Exception\HttpException"
file: "C:\xampp74new\htdocs\swms\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php"
line: 208
message: "CSRF token mismatch."

有很多方法只需嘗試一下(直接發送帶有數據的csrf令牌)

data: {
        "_token": "{{ csrf_token() }}",
     }

有2種可能:

  1. 來自 Ajax 的請求不匹配 CSRF 令牌參數,通過將 CSRF 令牌參數添加到您的請求來解決它$.extend( query, { '_token': 'your csrf token' });

  2. cookies 中XSRF-TOKEN不匹配。 在我的情況下,我通過更改config\session.php中的配置來解決它 將安全配置從true更改為false

I had the same issue, ajax requests were working fine on local and not on server which was on https, despite passing token in header in ajax setup and tried all other solution but no luck, @Giangimgs 's answer gave me the hint, my罪魁禍首是將 config/sessions.php 中的 http_only 值設置為 true,我將其更改為 false,並且在實時服務器上一切正常。 要設置為 false 的值的屏幕截圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM