12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- import axios from 'axios'
- import sso from './sso'
- import router from '@src/router/index'
- import type { AxiosInstance, CreateAxiosDefaults, AxiosRequestConfig } from 'axios'
- const config = {
- timeout: 60000,
- }
- const invalidCode = 1000
- class Request {
- private instance: AxiosInstance
- constructor(config: CreateAxiosDefaults) {
- this.instance = axios.create(config)
- this.instance.interceptors.request.use(function(config) {
- if (!config.headers.token) {
- const userInfo = sso.getUserInfo()
- config.headers.token = userInfo.token
- }
- return config
- }, function(error) {
- return Promise.reject(error)
- })
- this.instance.interceptors.response.use(function(response) {
- const { data } = response
- const { code } = data
- // 登陆过期 || 未登陆
- if (code === invalidCode) {
- sso.clearUserInfo()
- const {pathname,search} = location
- if (pathname!=='/login') {
- router.navigate('/login?redirectUrl='+ encodeURIComponent(pathname+search) )
- }
-
- return Promise.reject(data)
- }
- return data
- }, function(error) {
- return Promise.reject(error)
- })
- }
- get<T>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
- return this.instance.get(url, config)
- }
- getBlob<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
- return this.instance.get(url, config)
- }
- post<T>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<ApiResponse<T>> {
- return this.instance.post(url, data, config)
- }
- }
- export default new Request(config)
|