在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML/ 我在獲取驗證碼之前需要調驗證賬號和驗證圖片驗證碼的接口,只有這兩個接口succe

我在獲取驗證碼之前需要調驗證賬號和驗證圖片驗證碼的接口,只有這兩個接口success為true才能調短信驗證碼接口

圖片描述

目前我的處理方式趕緊有點笨...不知道怎么寫更優(yōu)化

getCode(){
 this.$post('賬號驗證api',{phone:this.phone}).then(res=>{
   if (res.success) {
     this.$post('圖片驗證api',{imgCode:this.imgCode}).then(res=>{
       if (res.success) {
         this.$post('短信驗證api',{SMSCode:this.Code}).then(res=>{
           if (res.success) {
                  
           }
         })
       }
     })
   }
 })
}
回答
編輯回答
淺淺

1.我覺得手機驗證可以在前端完成,沒必要傳到后臺驗證。這樣就可以少一個post
2.如果一定都要在前端,可以用Promise,我覺得可以稍微優(yōu)雅一點,類似于

let phonePro = new Promise(...),imgPro = new Promise(...);
Promise.all([phonePro,imgPro]).then(res=>{
    //res是一個數(shù)組
    if(res[0].success && res[1].success){
        ...//發(fā)送短信
    }
})

看不懂上面可以看MDN-Promise,相關api介紹

2017年6月16日 19:46
編輯回答
枕邊人

promise.all()

2017年9月9日 12:35
編輯回答
懷中人

一個接口就夠了:發(fā)送短信驗證碼的接口,把用戶名(手機號)、圖像驗證碼參數(shù)都帶上,先驗證這倆參數(shù),如果沒問題,就直接發(fā)短信;如果有問題就報錯。
沒有必要先調用兩次接口,分別校驗兩個參數(shù)。

2017年5月11日 04:06
編輯回答
命于你

啥也不廢話,直接上代碼:

getCode(){
     // 我覺得帳號驗證和圖片驗證可以并行:
     Promise.all([
         this.$post('賬號驗證api',{phone:this.phone}).then(res => {
             if (!res.success) throw new Error('帳號非法')
         }),
         this.$post('圖片驗證api',{imgCode:this.imgCode}).then(res=>{
             if (!res.success) throw new Error('圖片驗證碼非法')
         }),
     ]).then(() => {
         // 一定要注意return!
         return this.$post('短信驗證api',{SMSCode:this.Code}).then(res=>{
           if (!res.success) throw new Error("短信驗證碼非法!")
         })
     }).then(() => {
         // 繼續(xù)正常流程處理
     }).catch((err) => {
         // 處理異常,比如彈框:
         alert(err)
     })
 }
 

其實用async/await來寫更爽:

async getCode(){
     try {
         // 我覺得帳號驗證和圖片驗證可以并行:
         await Promise.all([
             this.$post('賬號驗證api',{phone:this.phone}).then(res => {
                 if (!res.success) throw new Error('帳號非法')
             }),
             this.$post('圖片驗證api',{imgCode:this.imgCode}).then(res=>{
                 if (!res.success) throw new Error('圖片驗證碼非法')
             }),
         ])
         
         const res = await this.$post('短信驗證api',{SMSCode:this.Code})
         if (!res.success) {
             throw new Error("短信驗證碼非法!")
         }
         
         // 繼續(xù)正常流程處理...
     } catch (err) {
         // 處理異常,比如彈框:
         alert(err)
     }
 }
 

對了,其實前端還可以做更多事情:

  1. 手機號碼格式校驗
  2. 圖片驗證碼校驗

當然這兩個校驗肯定服務端也要做,前端做用戶體驗會更好(速度更快)一些。

關于圖片驗證碼校驗,還要再啰嗦一下,別把圖片驗證碼直接返回給前端,而是應該返回個hash值(最好加鹽后的hash值)到前端,然后前端校驗用戶輸入的驗證碼的hash值與后臺返回的hash值是否一樣,不一樣就報錯。

2017年9月2日 06:04