【问题标题】:Laravel ajax 422 Unprocessable Entity even when token is matching即使令牌匹配,Laravel ajax 422 也无法处理实体
【发布时间】:2016-01-13 06:52:12
【问题描述】:

即使通过 Ajax 提交表单,我也会收到 422 Unprocessable Entity 错误。

我的 javascript 文件

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

$('.keywords-plan-form').submit(function(event) {
    event.preventDefault();

    $.ajax({
        url: '/laravel/public/keywordsplans',
        type: 'POST',
        data: $(this).serialize(),
        success: function(data){
            alert(data);
            // success logic
        },
        error: function(data){
            // Error...
            var errors = $.parseJSON(data.responseText);

            console.log(errors);

            $.each(errors, function(index, value) {

            });

        }
    });

});

如您所见,我在 ajax 标头中添加了 X-XSRF-TOKEN****strong text

这是我的''标签

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

我的 表单数据在 chrome 调试器中

_token:5j6DGhhTytbIRB1GrW9Wml9XrOxmKjgE9RiGa4Gf
date:
keyword[0]:Lorem ipsum
keyword[1]:Is dolor amet
keyword[2]:plumber tampa

请求标头

X-XSRF-TOKEN:5j6DGhhTytbIRB1GrW9Wml9XrOxmKjgE9RiGa4Gf
.....

我是做错了什么还是忘记了什么?

【问题讨论】:

    标签: ajax forms laravel-5


    【解决方案1】:

    我不认为 csrf 令牌是这里的问题。如果是,您将获得 TokenMissmatchException 而不是 Unprocessable Entity。 你的控制器中是否有这样的请求验证器?

        $validator = Validator::make($request->all(), [
    
                'username' => 'required|max:30|min:6|unique:users',
    
                'email' => 'required|email|max:50|unique:users',
    
                'password' => 'required|confirmed|min:6',
    
            ]);
    

    如果是这样,也许你可以这样做:

        if ($validator->fails()) {
    
                if($request->ajax())
                {
                    return response()->json(array(
                        'success' => false,
                        'message' => 'There are incorect values in the form!',
                        'errors' => $validator->getMessageBag()->toArray()
                    ), 422);
                }
    
                $this->throwValidationException(
    
                    $request, $validator
    
                );
    
            }
    

    之后,您可以像这样在 ajax 错误处理程序中捕获验证错误:

      $('.keywords-plan-form').submit(function(event) {
           event.preventDefault();
    
    $.ajax({
        url: '/laravel/public/keywordsplans',
        type: 'POST',
        data: $(this).serialize(),
        success: function(data){
            alert(data);
            // success logic
        },
        error: function(jqXhr, json, errorThrown){// this are default for ajax errors 
            var errors = jqXhr.responseJSON;
            var errorsHtml = '';
            $.each(errors['errors'], function (index, value) {
                errorsHtml += '<ul class="list-group"><li class="list-group-item alert alert-danger">' + value + '</li></ul>';
            });
            //I use SweetAlert2 for this
            swal({
                title: "Error " + jqXhr.status + ': ' + errorThrown,// this will output "Error 422: Unprocessable Entity"
                html: errorsHtml,
                width: 'auto',
                confirmButtonText: 'Try again',
                cancelButtonText: 'Cancel',
                confirmButtonClass: 'btn',
                cancelButtonClass: 'cancel-class',
                showCancelButton: true,
                closeOnConfirm: true,
                closeOnCancel: true,
                type: 'error'
            }, function(isConfirm) {
                if (isConfirm) {
                     $('#openModal').click();//this is when the form is in a modal
                }
            });
    
        }
    });
    });
    

    并查看消息中的 modal message

    【讨论】:

      【解决方案2】:

      我已经解决了这个问题:

      public function register(\Illuminate\Http\Request $request) {        
          if ($this->validator($request->all())->fails()) {
              $errors = $this->validator($request->all())->errors()->getMessages();            
              $clientErrors = array();
              foreach ($errors as $key => $value) {
                  $clientErrors[$key] = $value[0];
              }
              $response = array(
                  'status' => 'error',
                  'response_code' => 201,
                  'errors' => $clientErrors
              );            
          } else {
              $this->validator($request->all())->validate();
              $user = $this->create($request->all());
              $response = array(
                  'status' => 'success',
                  'response_code' => 200
              );
          }
          echo json_encode($response);
      }
      

      【讨论】:

        【解决方案3】:

        也许有人会派上用场。

        422 无法处理的实体

        是验证器 laravel 的默认错误

        vendor/laravel/framework/src/Illuminate/Validation/Validator.php
        

        如果验证参数失败,则通过异常验证异常

        vendor/laravel/framework/src/Illuminate/Validation/ValidationException.php
        

        默认状态 = 422

        因此,您所有带有非验证表单的 ajax 响应都将是 status = 422

        【讨论】:

          【解决方案4】:

          谁还在寻找答案,如果您使用 Lumen,请确保 Request 对象是 Illuminate\Http\Request 类型,而不是 Lumen 的默认类型。

          ```function create(Request $request){
          
          

          【讨论】:

            猜你喜欢
            • 2019-03-14
            • 2021-05-27
            • 1970-01-01
            • 1970-01-01
            • 2016-04-30
            • 1970-01-01
            • 2023-03-22
            • 2021-03-19
            相关资源
            最近更新 更多