axios请求封装
在utils
文件夹下新建http.ts
文件
import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
const defaultConfig = {
timeout:5000,//超时时间
baseUrl:''//设置公用路由
}
class HTTP{
constructor(){
this.httpInstanceRequest()
this.httpInstanceResponse()
};
// 初始化axios
private static axiosInstance = axios.create(defaultConfig)
// 请求拦截
private httpInstanceRequest(){
HTTP.axiosInstance.interceptors.request.use((config: AxiosRequestConfig)=>{
if(获取token){
config.headers.Authorization = `Bearer ${token}` // 后端定义的token格式
}
//做请求拦截处理
return config
},err=>{
return Promise.reject(err)
})
}
// 相应拦截
private httpInstanceResponse(){
HTTP.axiosInstance.interceptors.response.use((response:AxiosResponse)=>{
//做相应拦截处理
return response
},err=>{
return Promise.reject(err)
})
}
// 封装接口
// get
public httpRequestGet<T>(url:string, params:any):Promise<T>{
return HTTP.axiosInstance.get(url, params).then(res=>{
return res.data
}).catch()
}
// post
public httpRequestPost<T>(url:string, data:AxiosRequestConfig):Promise<T>{
return HTTP.axiosInstance.post(url, data).then(res=>{
return res.data
}).catch()
}
}
export const http = new HTTP()
在api
文件夹下新建index.ts
文件
import { http } from '../../utils/http'
interface RoomDetail{
id:string;
}
export function getRoomDetail(params: RoomDetail){
return http.httpRequestGet('room/room/getRoomDetail', {params})
}
最后在页面中引入index.ts
调用里面的getRoomDetail
方法传入对应的参数即可。