javascript - 无法自定义表单错误,因为服务器返回 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 network tab
我已经尝试了以下链接Issues with Axios catch method from Laracast
还有其他一些解决方案,但都没有解决我的问题。在使用之前async-await pattern
我使用过axios.post('url',data).then(res=>...).catch(err=>...)
当我使用邮递员时,http status
仍然是422
但error object
被退回了,所以postman
一切都很好但不在browser
我怎么解决这个问题?
解决方案
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
推荐阅读
- java - 我怎样才能摆脱以下突出显示的输出?
- flutter - webview_flutter 违反了内容安全政策,有什么解决办法吗?
- r - 如何使用 R 中 patchwork 包中的 inset_element() 函数嵌入地图
- webhooks - 通过 webhook 连接器更新 Teams 中的消息卡
- android - 使用改造 HttpException 捕获错误消息
- typescript - 可以使用数组值来创建具有相应字符串文字的键值类型吗?
- spring-boot - Spring Boot + grpc 日志记录 + 相关 ID?
- kotlin - 如何使用阻塞代码取消协程
- python - 用日期时间数据绘制 scipy.signal.find_peaks 图
- c# - 在gridview下计算总计