基於Typescript與Axios的介面請求管理詳解
阿新 • • 發佈:2021-09-14
目錄
- 思路
- 請求攔截
- 響應攔截
- 使用httpClient.ts定義請求
- 在元件中請求介面
- 總結
本文主要介紹基於TS和AXIOS的介面請求封裝
思路
請求攔截
- 在請求頭新增一些引數,例如token,uid等
- 判斷使用者登入狀態,如果沒有登入,直接跳轉登入
- 處理請求資料轉換髮送請求的資料格式,on→urlencoded (可選的)
響應攔截
- 判斷後端響應的業務狀態碼,進行不同的處理
- 例如使用者登入狀態過期,直接跳轉登入
- 統一的報錯提示
先把套路化的程式碼寫出來:
import axios,{ AxiosInstance,AxiosResponse,AxiosRequestConfig,AxiosError } from 'axios' export default abstract class HttpClient { protected readonly instance: AxiosInstance public constructor(baseURL = '/api',timeout = 1000 * 120) { this.instance = axios.create({ baseURL,timeout }) // 1. 請求攔截器 this._initializeRequestInterceptor() // 2. 響應攔截器 this._initializeResponseInterceptor() } private _initializeRequestInterceptor = () => { this.instance.interceptors.request.use( this._handleRequest,this._handleError ) } private _handleRequest = (config: AxiosRequestConfig) => {} private _initializeResponseInterceptor = () => { this.instance.interceptors.response.use( this._handleResponse,this._handleError ) } private _handleResponse = (response: AxiosResponse) => {} protected _handleError = (error: AxiosError) => Promise.reject(error) }
簡單說一下上面的程式碼,我們建立了一個用於請求介面的HttpClient類,在constructor中定義了baseURL和超時時間timeout,同時定義了請求攔截llYEDxcWF方法和響應攔截方法。
至此,發起一個介面的流程如下:
- 傳送請求之前,呼叫請求攔截
- 傳送介面,network出現請求
- 介面響應,呼叫響應攔截
- 響應給前端程式,執行對應的邏輯
請求攔截
下面開始詳細的邏輯,請求攔截的時候,可以做的事情如下:
- 在請求頭新增一些引數,例如token,uid等
- 判斷使用者登入狀態,如果沒有登入,直接跳轉登入
- 處理請求資料轉換髮送請求的資料格式,json→urlencoded (可選的)
private _handleRequest = (config: AxiosRequestConfig) => { //1. 新增自定義請求頭 config.headers['Authorization'] = 'my token' config.headers['mobile'] = 'my mobile' //2. 判斷是否登入(判斷是否有toke) //3. 轉化資料格式 config.data = qs.stringify(config.data) return config }
響應攔截
得到了響應之後,處理如下:
- 判斷後端響應的業務狀態碼,進行不同的處理
- 如果使用者登入狀態過期,直接跳轉登入
- 統一的報錯提示
- 儲存token
// 響應攔截器
private _handleResponse = (response: AxiosResponse) => {
const { data,headers } = response
//1.--處理響應的token,儲存token
const token = headers['authorization']
if (token) {
this._saveToken(token)
}
//2. --處理響應碼,這裡try-catch一下,如果後端有的介面沒有返回code,直接返回
try {
const code = data.code,message = data.desc || data.msg
llYEDxcWF const isSucceed = this._handleResCode(code,message,url)
if (isSucceed) {
return Promise.resolve(data)
} else {
return Promise.reject(message)
}
} catch (error) {
return Promise.resolve(data)
}
}
//儲存token
private _saveToken(token: string) {
const USER = getModule(UserModule)
USER.setToken(token)
}
private _handleResCode(code: number,message: string,url: string) {
if (code === 0) {
// 請求成功
return true
} else if (code===4000) {
// token失效,跳回登入介面
.prototype.$message.error('身份資訊過期,請重新登陸')
router.push({ name: 'login' })
return false
} else {
// 其他情況,統統提示message資訊
Vue.prototype.$message.error(message)
return false
}
}
使用httpClient.ts定義請求
建議請求相關的檔案定義在@/api目錄下面,目錄如下
httpClient.ts user.ts uti.ts
在對應的檔案中定義請求,注意事項
- 所有請求類需要繼承HttpClient類,HttpClient做了一些統一攔截統一處理請求及響應的工作
- 請求響應的資料需要提供型別,型別定義在@/types/xxx檔案中,一個模組對應一個檔案。只有提供了型別,才會有程式碼提示
import HttpClient from './HttpClient' import { AlarmItemType } from '../types/test' import { BaseResType } from '../types/index' class UtilApi extends HttpClient { //例如後臺返回的響應 res={code:xxx,data:xxx,token:xxx,desc:xxx} //首先需要定義 res.data 的型別 即get的第一個引數 AlarmItemType //然後需要定義整個響應的型別 即 BaseResType<AlarmItemType> public getAlarmById = (id: string) => this.instance.get<AlarmItemType,BaseResType<AlarmItemType>>( `/realtime/alarms/queryByAlarmId/${id}` ) } export const UTIL_API = new UtilApi()
在元件中請求介面
在需要傳送請求的元件中鍵入請求模組的關鍵字,例如USER_API,如果安裝了外掛TypeScript Importer,就會有相應的模組匯入提示,此時輸入回車即可匯入相應的模組。
<template>
<section>請求資料:{{ alarmData }}</section>
</templ客棧ate>
<script lang="ts">
import { UTIL_API } from '@/api/utilApi'
import { Vue,Component } from 'vue-property-decorator'
@Component({
components: {}
})
export default class TestRequest extends Vue {
alarmData = {}
async getAlarmData() {
const res = await UTIL_API.getAlarmById('alarmIdc7e9bd47')
if (res.code == 0) {
this.$message.success('請求成功')
this.alarmData = res.data
}
}
mounted() {
this.getAlarmData()
}
}
</script>
<style lang="s" scoped></style>
總結
到此這篇基於Typescript與Axios的介面請求管理的文章就介紹到這了,更多相關Typescript與Axios介面請求內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!