Home > Software engineering >  csrf-token mismatch error in laravel on server
csrf-token mismatch error in laravel on server

Time:12-07

I'm using this code to submit data through ajax in laravel

$('#submit').submit(function (e) {
    e.preventDefault();

    let formData = new FormData(this);

    $.ajaxSetup({
        headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
        xhr: function() {
          var xhr = new window.XMLHttpRequest();
      
          xhr.upload.addEventListener("progress", function(evt) {
            if (evt.lengthComputable) {
              var percentComplete = evt.loaded / evt.total;
              percentComplete = parseInt(percentComplete * 100);
             
      
              if (percentComplete === 100) {
               
              }
      
            }
          }, false);
      
          return xhr;
        },
        url: $(this).attr('action'),
        type: "POST",
        data:  formData,
        dataType:'JSON',
        contentType:false,
        cache: false,
        processData: false,

but getting csrf token mismatch when i upload my code on live server.

enter image description here

enter image description here

Any solution is highly appreciated Thanks

CodePudding user response:

I see you are fetching the token from the HTML page metatag, make sure your HTML page is not being cached by an intermediate/browser between accesses (try opening with two different browsers and checking the token, refreshing with f5 and force reloading too).

Another common issue is multiple HTML pages being loaded simultaneously (frames? maybe a 404 file that returns your default page, refreshing the token for your session). This is hard to find, check the network tab of your browser dev tools and inspect each response.

I don't think it's the case, but sometimes the case makes difference X-CSRF-Token if a proxy is "cleaning up non whitelisted headers".

  • Related