Vuex calls the Laravel interface to send a verification code to the user's mobile phone, the code is as follows:
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);
});
},
},
If the phone number has been registered, the response is like this,
but the error printed by the console is like this:
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
So we can't get the appropriate error message, my solution is this:
First get the response object:
console.log(error.response.data);
You can see that the response object contains our error message object errors. Our goal is to get the error message "phone already exists", which is the first value of the phone array under the errors object. I got it like this:
Use JavaScript's Object.keys(obj) method to get the first value of the phone array under the error.response.data.errors object, and then use toString() to convert it to a string:
Object.keys(obj)
Parameters: the object whose enumerated properties should be returned
Return value: a string array representing all enumerable properties of a given object
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() );
}