Laravel 中的 Ajax 419 状态错误

2024-01-30

enter image description hereI tried to upload images using AJax,Jquery,Laravel. Here I tried with so many solutions still I am getting 419 error and in some cases getting 500 internal error.

我尝试过的代码是

<form method="POST" id="needs" novalidate enctype="multipart/form-data">
            {{csrf_field()}}
                <input name="image1" id="image1" type="file" class="form-control" required="" />
                <br>
                <input type="file" name="image2" id="image2" class="form-control" required/>
                <br>
                <input type="file" name="image3" id="image3" class="form-control" required/>
                <br>
                <input type="file" name="image4" id="image4" class="form-control" required/>
                <br>
                <input type="file" name="image5" id="image5" class="form-control" required />
                <br>
                <button type="button" id="upload_image" name="upload_image" class="btn btn-lg btn-success" onclick="image_up();">Upload</button>
              </form>

Jquery:

function image_up()
{
  alert("Uploading start");
  $.ajax({
    headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
        url: "{{route('collage.store')}}",
        type: 'POST',
        data : new FormData($(this)[0]),
        dataType: "json",
        cache : false,
    processData: false,
        success: function () {
          alert('form was submitted');
        }
      });
  }

Route:

Route::post('/', 'CollagePrimController@post')->name('collage.store');

请任何人帮助我解决这个问题。提前致谢


Laravel 419 状态错误仅与令牌授权相关。

在您的 head 部分添加以下代码:

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

将以下代码添加到您的 ajax 调用中:

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

如果仍然出现 419 错误,则通过修改 app/Http/Middleware/VerifyCsrfToken.php 从特定路由禁用 CSRF 令牌

class VerifyCsrfToken extends BaseVerifier
{

 // The URIs that should be excluded from CSRF verification.

    protected $except = [
    "/*"
    ];
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Laravel 中的 Ajax 419 状态错误 的相关文章

随机推荐