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() );
}