我将axios
用于HTTP
,将Vue.js
用于ajax call
。但是,当我执行server
时,response data
发回{{ 1}}成功200
。但是,当出现错误时,server
不会执行catch bloc
。
这是我在Vue.js中的ajax调用
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',this.form);
console.log("Ba donnees : ",res.data);
}catch(err){
console.log("Erreeer",err.response);
}
}
}
}
这是我的注册控制器:
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);
}
一切正常后,我得到了try
的预期结果,但是对于POST http://localhost:5000/api/register 422 (Unprocessable Entity)
,它正在尝试将语句记录在try
中。
但是当我进入“网络”标签时,会看到返回的错误JSON
{“ message”:“给定的数据无效。”,“ errors”:{“ fname”:[“ fname 字段为必填。“],” lname“:[” lname字段为 必填。“],”城市“:[”必填城市字段。“],”电子邮件“:[”电子邮件 必填字段。“],”密码“:[”必填密码字段。“]}}
答案 0 :(得分:2)
返回http错误时,Axios不会发送异常,您应该改用axios.catch:
axios
.post('api/register',this.form);
.then(res => { console.log("Ba donnees : ",res.data) })
.catch(err => { console.log("Erreeer",err.response) });
答案 1 :(得分:0)
您可以定义何时应使用validateStatus属性捕获响应,像这样
axios.post('api/register', {
validateStatus: function (status) {
return status < 400; // Reject only if the status code is greater than or equal to 400
}
})