赞
踩
① baseURL:设置url的基本结构(请求根地址),域名和协议,再结合属性url某个请求路径,axios会自动将baseURL 和 url 进行拼接,从而得出正确的请求路径。
② method:请求方式 get/post
③ timeout:延时时间(超过多少时间就取消请求)【单位是毫秒】
// 请求时的基础配置VITE_APP_BASE_URL export const URLMap = { base: import.meta.env.MODE === 'development' ? import.meta.env.VITE_APP_BASE_URL : (window as any).config.VITE_APP_BASE_URL, pdf:import.meta.env.MODE === 'development' ? import.meta.env.VITE_APP_BASE_URL_PDF : (window as any).config.VITE_APP_BASE_URL_PDF, } const REQUESTS : Record<string, AxiosInstance> = {} declare module 'axios' { interface AxiosResponse<T = any> { errorinfo: null doc: any time: any x: any y: any } export function create(config?: AxiosRequestConfig): AxiosInstance } Object.keys(URLMap).forEach((item) => { const REQUEST: AxiosInstance = axios.create({ baseURL: URLMap[item], headers: { 'Content-Type': 'application/json;charset=UTF-8', }, timeout: 300000, withCredentials: item === 'data', }) REQUESTS[item] = REQUEST }) // 请求拦截器 Object.keys(REQUESTS).forEach((item) => { REQUESTS[item].interceptors.request.use(async (config: AxiosRequestConfig) => { const headerToken = await getToken() config.headers = config.headers || {} if (headerToken) config.headers.Authorization = headerToken if (config.headers.type === 'form') { delete config.headers.type config.data = qs.stringify(config.data) config.headers['Content-Type'] = 'application/x-www-form-urlencoded' } return config }) }) // 响应拦截器 Object.keys(REQUESTS).forEach((item) => { REQUESTS[item].interceptors.response.use( async (response: AxiosResponse) => { const { status, data = {}, statusText } = response const errorText = serverCodeMessage[status] || statusText const error = '' if (status) return Promise.resolve(data) message.error(error) return Promise.reject(error) }, (error) => { message.error(String(new Error(error))) return Promise.reject(new Error(error)) }, ) }) export default REQUESTS
import requests from '@/service/index'
export const getAll = (data: paramsInter) => requests.base({
url: 'xx/xx',
method: 'POST',
data,
})
export const get = (data: paramsInter) => requests.pdf({
url: 'xx/xx',
method: 'POST',
data,
})
这样,不同的接口实现从不同的服务器获取资源
import { getAll} from '@/service/xx/index'
onMounted(() => {
getXX()
})
function getXX() {
getAll(params).then((res) => {
// xxx
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。