我如何从ajax错误方法获取json响应

时间:2018-12-12 17:04:51

标签: ajax laravel axios

我试图使用vue和laravel创建用户身份验证,单击注册按钮后,我会将表单数据发送到以这种方式编码的创建用户控制器

public function store(Request $request)
{
    //

    $validator = Validator::make($request->all(), [
        'firstname'  =>  'required',
        'lastname'   =>  'required',
        'email'      =>  'required|email|unique:users',
        'password'   =>  'required|min:8',
        'phoneno'    =>  'required'
    ]);

    if ($validator->fails()){
        return response($validator->getMessageBag()->jsonSerialize(), Response::HTTP_UNPROCESSABLE_ENTITY); 
    }

    $firstname = $request->firstname;
    $lastname = $request->lastname;
    $email = $request->email;
    $password = $request->password;
    $phoneno = $request->phoneno;
    return response($request, Response::HTTP_OK);
}

从前端,我正在使用axios进行ajax请求,我将表单数据发送为:

    let formdata = this.user;
    axios.post('/api/user', {
        data: formdata
    }).then((data) => {
        console.log(data);
    })
    .catch((error) => {
        console.log(error);
    });

但是在出现错误的情况下,我无法获取从 $validator->fails()检查我只会看到: image from registering with errors

有没有办法获取错误传递的json?

1 个答案:

答案 0 :(得分:1)

类似这样的东西:

return response()->json($validator->errors(), Response::HTTP_UNPROCESSABLE_ENTITY)

编辑:

error.response.data出现错误消息

error.response.status的错误代码