【问题标题】:Unable to customize form errors because server is returning 422 Unprocessable Entity without returning errors无法自定义表单错误,因为服务器返回 422 Unprocessable Entity 而没有返回错误
【发布时间】:2019-07-29 02:38:43
【问题描述】:

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

这是我的后端代码:

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 network tab

我尝试了来自 Laracast

的以下链接 Issues with Axios catch method

how to display the errors in .catch coming from an api on frontend

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

当我使用邮递员时,http status 仍然是422,但返回了error object,所以使用postman 一切正常,但不在browser

我该如何解决这个问题?

【问题讨论】:

  • 这不是duplicate 那里他使用vuejs $http api
  • 您得到的错误是server 错误。与HTTP客户端无关
  • 当我使用 postman 时一切正常,error object 被返回
  • 请在 Postman 中发布您发送的有效负载,这将有很大帮助

标签: javascript laravel vue.js axios http-status-code-422


【解决方案1】:

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

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

$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);

}

在您的代码中,应检查来自register 函数的$data 变量是否验证失败并返回错误

【讨论】:

  • 如果我发送的数据有问题,我也会在验证成功的情况下遇到问题。验证成功后,返回用户数据并将数据存储到数据库中跨度>
  • @jochri3 你是说你仍然得到HTTP 422,但数据仍然保存在数据库中?
  • 不,我说过如果HTTP 422 数据没有存储到database,但我无法访问console 中的error object。但是当我的表格很好时,每个归档的填充数据被存储,user object 被返回,我可以在console 中访问它
  • 对不起,我很难理解您的拼写,但据我所知,这似乎仍然是一个验证错误。您可以发布一个 JSON 或发送到服务器的数据的屏幕截图吗?
  • {email: "", password: "", password_confirmation: "", fname: "", lname:"",fname:"",lname:"",city:""}
【解决方案2】:

这是因为err直接访问时会返回toString()方法,但是有属性:

err.response.data 将拥有您要查找的内容。

【讨论】:

  • 它不起作用。它说Cannot read property 'data' of undefined
  • Cannot read property 'data' of undefined 是我尝试登录error.reponse时控制台给出的信息
  • 那是因为res 没有属性data。它是从上面的代码中抛出的 ^.
  • 这里没有什么,res.data 甚至不应该被执行,因为在catch bloc 中捕获了错误。所以尝试在try 中抛出error 是不正常的行为
【解决方案3】:

当出现 HTTP 错误(例如响应码在 400 到 599 之间)时,axios 会返回 axios 错误响应,并且在错误处理下的 repository documentation 中表示您可以使用 error.response.data 访问实际响应。例如:

 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){
       if (err.response && err.response.status === 422) {
           if (err.response.data.errors.fname) {
              console.log('First name errors: '+ err.response.data.errors.fname.join(','));
           } 

           // and so on

       }
   }

【讨论】:

  • 这一行 if (err.response && err.response.status === 422) 在检查 err.response.status 之前检查是否定义了 err.response。如果err.response 未定义,那么这意味着您实际上没有HTTP 错误,而是另一种错误。在您最初共享的控制台中,还有一行 Cannot read property 'data' of undefined 是错误但不是 HTTP 错误,因此它也会被捕获在 catch 块中,因此您应该尝试区分这两种情况
【解决方案4】:

当 Axios 抛出错误时,可以在error.response 中找到 HTTP 响应。验证错误将在 errors 键中,因此您可以访问如下验证错误:

axios.post(someUrl, someData)
    .then(response => {
        // Successful response
    })
    .catch(error => {
        let errors = error.response.data.errors;
    });

【讨论】:

  • error.response 是 axios 响应,所以实际数据在 error.response.data
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
  • 2018-06-30
  • 2019-06-08
  • 2021-03-03
  • 2013-07-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多