Vuex 调用 Laravel 接口向用户手机发送验证码,代码如下:
actions: {
sendVerificationCodes( {
commit },data ){
commit( 'sendVerificationCodes', 1 );
SupcellAPI.sendVerificationCodes(data)
.then( function( response ){
commit( 'sendVerificationCodes', 2 );
commit( 'setVerificationKey' ,response.data.key);
})
.catch( function(error){
commit( 'sendVerificationCodes', 3 );
console.log(error);
});
},
},
如果手机号已经被注册,响应是这样的,
但是控制台打印出的错误竟然是这样的:
Error: "Request failed with status code 422"
createError http://www.supcell.info/js/app.js?id=7ccb2b826fa7b1791d65:784
settle http://www.supcell.info/js/app.js?id=7ccb2b826fa7b1791d65:1045
handleLoad http://www.supcell.info/js/app.js?id=7ccb2b826fa7b1791d65:253
app.js:83151:17
这样我们无法获取到合适的错误信息,我的解决办法是这样的:
首先获取响应对象:
console.log(error.response.data);
可以看到响应对象里包含了我们的错误信息对象 errors ,,我们的目标是获取"电话已经存在"这个错误信息,他是 errors 对象下面的 phone 数组的第一个值,我是这样获取的:
使用 javascript 的Object.keys(obj)方法, 获取 error.response.data.errors 对象下面的 phone 数组的第一个值,然后 使用 toString() 转为字符串:
Object.keys(obj)
参数:要返回其枚举自身属性的对象
返回值:一个表示给定对象的所有可枚举属性的字符串数组
if(typeof error.response.data.errors === "undefined"){
commit( 'setVerificationCodesSendErrors',error.response.data.message);
}else{
commit( 'setVerificationCodesSendErrors', error.response.data.errors[Object.keys(error.response.data.errors)[0]].toString() );
}