ts通过class类封装axios
ts通过class类封装axios一、axios 安装npm i axios -S二、HttpRequest类封装// 文件 utils/axios.tsimport axios, {AxiosInstance, AxiosRequestConfig} from 'axios'class HttpRequest {private readonly baseUrl: string;construct
·
ts通过class类封装axios
一、axios 安装
npm i axios -S
二、HttpRequest类封装
// 文件 utils/axios.ts
import axios, {AxiosInstance, AxiosRequestConfig} from 'axios'
class HttpRequest {
private readonly baseUrl: string;
constructor() {
this.baseUrl = 'http://localhost:3000'
}
getInsideConfig() {
const config = {
baseURL: this.baseUrl,
headers: {
//
}
}
return config
}
// 请求拦截
interceptors(instance: AxiosInstance, url: string | number | undefined) {
instance.interceptors.request.use(config => {
// 添加全局的loading..
// 请求头携带token
return config
}, (error: any) => {
return Promise.reject(error)
})
//响应拦截
instance.interceptors.response.use(res => {
//返回数据
const {data} = res
console.log('返回数据处理',res)
return data
}, (error: any) => {
console.log('error==>',error)
return Promise.reject(error)
})
}
request(options: AxiosRequestConfig) {
const instance = axios.create()
options = Object.assign(this.getInsideConfig(), options)
this.interceptors(instance, options.url)
return instance(options)
}
}
const http = new HttpRequest()
export default http
三、接口方法封装
// 文件api/index.ts
import http from '../utils/axios'
export const menuList =()=>{
return http.request({
url: '/users/menuList',
method: 'get'
})
}
四、页面使用
import {menuList} from '../api/index'
getMenuList(){
menuList().then(res=>{
console.log(res)
})
}
更多推荐
已为社区贡献1条内容
所有评论(0)