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);
応答オブジェクトにエラーメッセージオブジェクトエラーが含まれていることがわかります。目標は、エラーオブジェクトの下にある電話配列の最初の値であるエラーメッセージ「phonealreadyexists」を取得することです。次のように取得しました。
JavaScriptのObject.keys(obj)メソッドを使用して、error.response.data.errorsオブジェクトの下にある電話配列の最初の値を取得し、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() );
}