直接上代碼
import { useUserStore } from '@/store'
import { ElMessage } from 'element-plus'
import type { Method, AxiosRequestConfig } from 'axios'
import axios from 'axios'
const server = axios.create({
baseURL: '要替換的url',
timeout: 5000
})
server.interceptors.request.use(
(config) => {
const store = useUserStore()
let token = store.token
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
},
(err) => Promise.reject(err)
)
server.interceptors.response.use(
(res) => {
return res.data
},
(err) => {
const store = useUserStore()
if (err.response.data.code === '403' || err.response?.data?.msg === 'Token已過期') {
// ElMessage.error(err.response?.data?.msg)
store.logout()
} else {
ElMessage.error(err.response?.data?.msg)
}
return Promise.reject(err)
}
)
type Data<T> = {
code: string
data: T
message: string
config?: AxiosRequestConfig
}
// 第一個T代表著我請求的返回的指定類型岭皂,第二個代表著 就是后端接口常見的返回格式 第三個攜帶的參數(shù)
//第四個就是特殊的請求格式输涕,比如你要上傳圖片視頻 需要的格式是 'Content-Type': 'multipart/form-data'
const request = <T>(url: string, method: Method = 'get', submitData?: object, config?: object) => {
const defaultConfig: AxiosRequestConfig = {
url,
method,
// 區(qū)分get和其他請求post
// get 提交數(shù)據(jù)潮饱,選項:params
// 其他請求post 提交數(shù)據(jù)搓译,選項:data
[method.toLowerCase() === 'get' ? 'params' : 'data']: submitData
// ...(其他默認(rèn)配置从隆,如果有的話)
}
const finalConfig = Object.assign({}, defaultConfig, config)
return server.request<T, Data<T>>(finalConfig)
}
export { server, request }
在你封裝的api請求中這樣使用:
import { request } from '@/utils/request'
import type { GoodsResult, GoodsItem, GoodsDetailsResult, GoodsSelectTypeItem, AddGoodsParams } from '@/types/goods'
// 獲取分類的全部商品
export const getGoodsTotal = (params: { categoryId: string }) => {
return request<GoodsItem[]>('/fly-code/productInfo/list', 'get', params)
}
// 購買商品
export const buyGoods = (data: { productId: number; quantity: number }) => {
return request('/fly-code/order/add', 'post', data)
}
// 上傳商品圖片
export const uploadGoodsImg = (data: FormData) => {
return request<string>('/fly-code/user/upload', 'post', data, { 'Content-Type': 'multipart/form-data' })
}