首页 > 解决方案 > 无法自定义表单错误,因为服务器返回 422 Unprocessable Entity 而没有返回错误

问题描述

我正在使用 Laravel 和 VueJS,对于我的所有post方法,put服务器在提交表单后返回新创建的数据,如果出现错误,我无法从browser console. 这是我在newtwork tab.The 中可以看到的。目的是根据服务器返回的错误自定义表单错误

这是我的后端代码:

private function validateForm($data){
    return Validator::make($data,
    [
        'fname' => ['required', 'string','min:2' ,'max:255'],
        'lname' => ['required', 'string','min:2' ,'max:255'],
        // 'mname' => ['string','min:2' ,'max:255'],
        'company' => ['string','min:2' ,'max:255'],
        'title' => ['string','min:2' ,'max:255'],
        'phone_number' => ['string','min:13' ,'max:13'],
        'city' => ['required', 'string','min:2' ,'max:100'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:8', 'confirmed']
        // 'password_confirm'=>['required','string']
    ]
  )->validate();
}
//Register
public function register(Request $request){
    $data=$this->validateForm($request->all());
    $data['password']=Hash::make($data['password']);
    $user=new User($data);
    $user->save();
    return response()->json($user);

}  

还有我的前端代码:

export default{
    data(){
        return {
            form:{
                email:'',
                password:'',
                password_confirmation:'',
                fname:'',
                lname:'',
                city:''
            },
            formError:''
        }
    },
    methods:{
        //This should be a POST method through axios
        register:async function(){
           try{
               const res=await axios.post('api/register',
               {
                   email:this.form.email,
                   password:this.form.password,
                   password_confirmation:this.form.password_confirmation,
                   fname:this.form.fname,
                   lname:this.form.lname,
                   city:this.form.city
               });
               //Une fois inscrit,il est redirige vers la page de login
               this.$router.push({path:'/login'});
               console.log("My data : ",res.data);
           }catch(err){
                   console.log("Errors",err);
           }

        }
    }
    }

当没有错误时,一切都很好,但是当有错误时,这就是我得到的browser console tab

Devtools 控制台选项卡

而在Devtools network tab

Devtools 网络选项卡

我已经尝试了以下链接Issues with Axios catch method from Laracast

如何在 .catch 中显示来自前端 api 的错误

还有其他一些解决方案,但都没有解决我的问题。在使用之前async-await pattern我使用过axios.post('url',data).then(res=>...).catch(err=>...)

当我使用邮递员时,http status仍然是422error object被退回了,所以postman一切都很好但不在browser

邮递员测试

我怎么解决这个问题?

标签: javascriptlaravelvue.jsaxioshttp-status-code-422

解决方案


HTTP 422 - Unprocessable Entity当你设置的验证失败时,Laravel 会返回。在您的情况下,我会仔细查看您发布到服务器的数据,并手动检查它是否通过了您编写的验证案例。

要获取导致错误的确切字段,您需要在代码中处理此问题,例如:

$validator = Validator::make($data, $rules);

if ($validator->fails()) {

  // 500 is the HTTP Status Code you want to return.   
  // This should also throw you in the catch branch of your front-end code
  return response()->json(['errors'=>$validator->errors()], 500);

}

在您的代码中,如果验证失败并返回错误,则应检查函数中的$data变量register


推荐阅读