63 lines
2.0 KiB
TypeScript
63 lines
2.0 KiB
TypeScript
|
|
import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'
|
|||
|
|
|
|||
|
|
class HttpRequest {
|
|||
|
|
getInsideConfig() {
|
|||
|
|
const config = {
|
|||
|
|
baseURL: '/api', // 所有的请求地址前缀部分(没有后端请求不用写)
|
|||
|
|
timeout: 80000, // 请求超时时间(毫秒)
|
|||
|
|
|
|||
|
|
// headers: {
|
|||
|
|
// 设置后端需要的传参类型
|
|||
|
|
// 'Content-Type': 'application/json',
|
|||
|
|
// 'token': x-auth-token',//一开始就要token
|
|||
|
|
// 'X-Requested-With': 'XMLHttpRequest',
|
|||
|
|
// },
|
|||
|
|
}
|
|||
|
|
return config
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 请求拦截
|
|||
|
|
interceptors(instance: AxiosInstance, url: string | number | undefined) {
|
|||
|
|
instance.interceptors.request.use(
|
|||
|
|
config => {
|
|||
|
|
const token: string | undefined = '' //getToken() //此处换成自己获取回来的token,通常存在在cookie或者store里面
|
|||
|
|
// 请求头携带token
|
|||
|
|
if (token) {
|
|||
|
|
config.headers['Authorization'] = token
|
|||
|
|
config.headers.Authorization = +token
|
|||
|
|
} else {
|
|||
|
|
config.headers['Authorization'] = 'Basic bmpjbnRlc3Q6bmpjbnBxcw=='
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
return config
|
|||
|
|
},
|
|||
|
|
(error: any) => {
|
|||
|
|
return Promise.reject(error)
|
|||
|
|
}
|
|||
|
|
)
|
|||
|
|
//响应拦截
|
|||
|
|
instance.interceptors.response.use(
|
|||
|
|
res => {
|
|||
|
|
//返回数据
|
|||
|
|
const { data } = res
|
|||
|
|
console.log('返回数据处理', data)
|
|||
|
|
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 request = new HttpRequest()
|
|||
|
|
export default request
|