32 lines
924 B
TypeScript
32 lines
924 B
TypeScript
import type { IRequestOptions } from '../types'
|
||
import { useUserStore } from '@/stores/user'
|
||
import { APP_INFO } from '@/api/config'
|
||
|
||
export function requestInterceptor(options: IRequestOptions): IRequestOptions {
|
||
const headers = { ...(options.headers || {}) }
|
||
|
||
// 更明确地调用 useUserStore
|
||
let token = ''
|
||
try {
|
||
const userStore = typeof useUserStore === 'function' ? useUserStore() : null
|
||
token = userStore?.token || uni.getStorageSync('token') || ''
|
||
} catch (e) {
|
||
token = uni.getStorageSync('token') || ''
|
||
}
|
||
|
||
if (token) headers.token = token
|
||
|
||
// Content-Type:只有在没有 files 时才默认为 application/json
|
||
if (!options.files && !headers['Content-Type']) {
|
||
headers['Content-Type'] = 'application/json;charset=UTF-8'
|
||
}
|
||
|
||
headers['appType'] = APP_INFO.TYPE
|
||
headers['version_code'] = APP_INFO.VERSION_CODE || '1.0.0'
|
||
|
||
return {
|
||
...options,
|
||
header: headers,
|
||
}
|
||
}
|