本文介绍了Laravel中的Ajax 419状态错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用AJax,Jquery,Laravel上传图片.在这里,我尝试了很多解决方案,但仍然出现419错误,在某些情况下仍然出现500内部错误.

I 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::post('/', 'CollagePrimController@post')->name('collage.store');

请任何人帮助我解决此问题.预先感谢

Please anyone help me to fix this issue. Thanks in advance

推荐答案

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

Laravel 419 status error is associated with token authorization only.

在您的头部添加以下代码:

Add below code in your head section:

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

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

Add keep below code to your ajax call:

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

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

If still 419 error is coming then disable CSRF token from specific routes by modifying app/Http/Middleware/VerifyCsrfToken.php

class VerifyCsrfToken extends BaseVerifier
{

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

    protected $except = [
    "/*"
    ];
}

这篇关于Laravel中的Ajax 419状态错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 20:35