基于vue2.x實(shí)現(xiàn)的即時(shí)通訊程序仿微信聊天5對(duì)接logo、getInfo接口

  • 前言:我們已經(jīng)開發(fā)好了登錄注冊(cè)頁(yè)面和通訊錄頁(yè)面以及聊天詳情頁(yè)面
  • 下面準(zhǔn)備接入登錄注冊(cè)和獲取用戶信息接口
  • 先打開接口文檔 備用https://www.showdoc.com.cn/2035654172307363/9196984446696982
  • 打開項(xiàng)目 的src/permission.js,把白名單內(nèi)無關(guān)的路由刪掉,只保留【'/login'
const whiteList = ['/login'] // no redirect whitelist
  • 下面打開src/api/index.js,修改api對(duì)象內(nèi)的【Login】的接口路徑和【UserInfo】的接口路徑
  • 改為我們的接口地址
const api = {
  Login: '/api/login',
  UserInfo: '/api/getInfo',
  UserName: '/user/name'
}

export default api
  • 然后打開src/api/user.js,就可以看到我們登錄方法和獲取用戶信息方法就靜靜等躺在那里,你想用,直接引入用起就是~
image.png
  • 下面開始配置反向代理解決跨域
  • 打開項(xiàng)目的src/vue.config.js,找到下圖中的代碼,把注釋打開
  • 注意 proxy前面 要用 逗號(hào) 隔開

image.png
  • 修改target為https://yyds.it98k.cn
proxy: {
      //配置跨域
      '/api': {
          target: "https://yyds.it98k.cn",
          // ws:true,
          changOrigin:true,
          pathRewrite:{
              '^/api':'/'
          }
      }
}
  • 然后修改環(huán)境變量
  • 打開src/config/env.development.js,修改baseApi的value值為/api
image.png
  • 然后重啟項(xiàng)目,才會(huì)生效

  • 下面
  • 打開src/utils/request.js
  • 在該文件頂部引入getToken方法
import { getToken,setToken,removeToken } from '@/utils/auth';
  • 在該文件中找到if (res.status && res.status !== 200)修改為if (res.code && res.code !== 200)
if (res.code && res.code !== 200) {
      // 登錄超時(shí),重新登錄
      if (res.code === 401) {
        store.dispatch('FedLogOut').then(() => {
          location.reload()
        })
      }
      return Promise.reject(res || 'error')
}
  • 下面開始接入登錄接口

  • 打開src/views/login/index.vue
  • 找到登錄按鈕觸發(fā)的方法handlerLogin
  • 在handlerLogin方法里寫邏輯
if (this.username.trim() === '') {
        this.$toast.fail('用戶名不能為空')
        return
      }
      if (this.password.trim() === '') {
        this.$toast.fail('密碼不能為空')
        return
      }
      this.$store.dispatch('login', {username:this.username,password:this.password}).then(() => {
          this.$router.push({ path: '/' })
      }).catch(err => {
          this.$toast.fail(err.message)
      })
  • 分析:先進(jìn)行非空校驗(yàn),用戶名和密碼不能為空
  • 然后校驗(yàn)通過直接使用dispatch觸發(fā)vuex內(nèi)的login方法
  • vuex內(nèi)現(xiàn)在還沒有定義login方法,需要去vuex內(nèi)新建該方法,假設(shè)登錄成功,直接跳轉(zhuǎn)到首頁(yè),假設(shè)登錄失敗,就彈出錯(cuò)誤信息,比如賬號(hào)密碼錯(cuò)誤
  • 下面就去vuex內(nèi)新建login方法
  • 打開src/store/modules/app.js,在actions里新建登錄方法
  • actions

 // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        commit('SET_TOKEN', response.token)
        setToken(response.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  • 因?yàn)橛玫搅说卿浗涌赼pi方法login和獲取用戶信息接口api方法getUserInfo,和 setToken 方法以及會(huì)用到setToken,removeToken,所以要導(dǎo)入需要用到的方法,此外還用到了SET_TOKEN常量方法,要在mutations內(nèi)新建該方法
import { login,getUserInfo } from "@/api/user"
import { getToken,setToken,removeToken } from "@/utils/auth"
  • state

const state = {
  userInfo: '',
  token:getToken()
}
  • mutations

const mutations = {
  SET_USER_NAME(state, userInfo) {
    state.userInfo = userInfo
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
}
  • getters.js

const getters = {
  userInfo: state => state.app.userInfo,
  token: state => state.app.token,
}
export default getters
  • 這時(shí)候,輸入錯(cuò)誤的賬號(hào)密碼登錄,會(huì)提示錯(cuò)誤信息
image.png
  • 輸入正確的賬號(hào)密碼,會(huì)死循環(huán),報(bào)錯(cuò)如下
image.png
  • 這是因?yàn)?,登錄成功后,觸發(fā)了permission.js里面的邏輯
image.png
  • 而vuex內(nèi)并沒有getUserInfo這個(gè)方法,所有一直在死循環(huán)報(bào)錯(cuò)!
  • 下面回到vuex內(nèi)新建getUserInfo方法
  • actions

getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(response => {
        const { data } = response
        
        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { username } = data

        commit('SET_USER_NAME', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  • 下面修改下permission.jsconst hasGetUserInfo = store.getters.userInfo
  • 改成如下
const hasGetUserInfo = store.getters.userInfo
  • 然后輸入正確的賬號(hào)密碼點(diǎn)擊登錄
  • 下面會(huì)報(bào)錯(cuò)
image.png
  • 通過排查發(fā)現(xiàn),getInfo接口確實(shí)觸發(fā)了,但是后端返回401,token失效,并且報(bào)錯(cuò)信息提示unknown action type: FedLogOut,找到報(bào)錯(cuò)的位置,發(fā)現(xiàn),我們的響應(yīng)攔截函數(shù)攔截到了401狀態(tài)碼,觸發(fā)了如下的邏輯
// 登錄超時(shí),重新登錄
      if (res.code === 401) {
        store.dispatch('FedLogOut').then(() => {
          location.reload()
        })
      }
  • 該段代碼的意思是,捕獲到401狀態(tài)碼后,觸發(fā)了vuex內(nèi)的FedLogOut方法
  • 而vuex內(nèi)并沒有這個(gè)方法,所以,要回到vuex內(nèi)新建FedLogOut方法
  • actions

// remove token
  FedLogOut({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      resolve()
    })
  }
  • 這時(shí)候,輸入正確的賬號(hào)密碼登錄還是登錄不成功,原因是因?yàn)槲覀儧]有傳給后端token,需要修改下如下
  • 打開src/utils/request.js的請(qǐng)求攔截器內(nèi)的config.headers['X-Token'] = ''
  • 改成config.headers['token'] = getToken()
  • 現(xiàn)在再去輸入正確的賬號(hào)密碼登錄,就可以
  • 【登錄成功了】!!!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容