import axios, { RawAxiosRequestHeaders, AxiosResponse, Method, InternalAxiosRequestConfig } from "@ohos/axios"
import { PostUserInfoPayLoad } from '../types/Api'
export class AxiosUtil {
private static instance: AxiosUtil = new AxiosUtil()
private constructor() {
// 请求拦截器
axios.interceptors.request.use((config: InternalAxiosRequestConfig) => {
// config.headers['Content-Type'] = 'application/json'
config.headers['authorization'] = (AppStorage.get("userinfo") as PostUserInfoPayLoad)?.token
// config.headers['authorization'] =
// "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuaWNrbmFtZSI6Ium7mOiupOeUqOaItyIsImF2YXRhciI6ImFjZTQxMTU3NDNkNTgxYjYwYjM0ZjlhOTM0NTVlNTFjLmpwZWciLCJhdmF0YXIyIjoiaHR0cDovL3RtcDAwMDAyLmxlYXJ2LmNvbS9hY2U0MTE1NzQzZDU4MWI2MGIzNGY5YTkzNDU1ZTUxYy5qcGVnIiwib3BlbmlkIjoib010a281RE9QTktQLXVXRDVTZzMwdzlfTzQ3TSIsInVzZXJfaWQiOjUsImlhdCI6MTY5OTg3MTY4NX0.lm6kd0AhNnaXV-9SXu1xXkfTWZ0LTSX0zGTk6am0tsc"
return config
})
// 响应拦截器
axios.interceptors.response.use((response: AxiosResponse) => {
return response.data
})
}
// axios: AxiosInstance
create(baseUrl?: string) {
axios.defaults.baseURL = baseUrl
console.log(axios.defaults.baseURL)
}
public static getInstance(url: string) {
AxiosUtil.instance.create(url)
return AxiosUtil.instance
}
async request<D, T>(method: Method = 'get', path: string, data?: D, headers?: RawAxiosRequestHeaders): Promise<T> {
return await axios.request({
url: path,
method,
data,
headers
})
}
async post<D, T>(path: string, data?: D, headers?: RawAxiosRequestHeaders): Promise<T> {
return await axios.post(path, data, { headers })
}
async get<T>(path: string, headers?: RawAxiosRequestHeaders): Promise<T> {
return await axios.get(path, { headers })
}
}
export const Request = AxiosUtil.getInstance('http://xxx')
鸿蒙开发——网络请求封装request
于 2024-08-29 15:05:46 首次发布