| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- import axios from 'axios'
- import { v4 as uuidv4 } from 'uuid'
- 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
- }
- config.headers['X-Timestamp'] = Date.now().toString()
- config.headers['X-Nonce'] = uuidv4()
- 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)
|