即使令牌匹配,Laravel ajax 422也是不可处理的实体

时间:2015-10-15 00:36:07

标签: ajax forms laravel-5

即使我通过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) {

            });

        }
    });

});

如您所见,我将 X-XSRF-TOKEN ****强文添加到ajax标题中。

这是我的''代码

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

我在chrome debuger中的表单数据

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

请求标题

X-XSRF-TOKEN:5j6DGhhTytbIRB1GrW9Wml9XrOxmKjgE9RiGa4Gf
.....
我做错了什么或遗忘了什么?

4 个答案:

答案 0 :(得分:4)

我不认为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

答案 1 :(得分: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);
}

答案 2 :(得分:0)

也许有人会派上用场。

  

422无法处理的实体

是验证程序laravel的默认错误

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

如果验证参数失败,则通过Exception ValidationException

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

默认状态为422

所有带有非验证表单的ajax响应都将具有状态= 422

答案 3 :(得分:0)

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

```function create(Request $request){