| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- import { env, TIMEOUT } from '@/common/env.uts'
- export type ApiResponse<T> = {
- code : number
- message : string
- data : T | null
- }
- export type RequestOptions = {
- url : string
- method ?: string
- data ?: UTSJSONObject | null
- header ?: UTSJSONObject | null
- showLoading ?: boolean
- }
- function getToken() : string {
- const token = uni.getStorageSync('token')
- if (token == null) return ''
- return token as string
- }
- export function request<T>(options : RequestOptions) : Promise<T> {
- return new Promise<T>((resolve, reject) => {
- const header : UTSJSONObject = options.header ?? {}
- header['Content-Type'] = 'application/json'
- const token = getToken()
- if (token.length > 0) {
- header['Authorization'] = 'Bearer ' + token
- }
- uni.request({
- url: env.baseUrl + options.url,
- method: options.method ?? 'GET',
- data: options.data,
- header: header,
- timeout: TIMEOUT,
- success: (res) => {
- const statusCode = res.statusCode
- if (statusCode >= 200 && statusCode < 300) {
- const body = res.data as UTSJSONObject
- const code = body.getNumber('code')
- if (code != null && code == 200) {
- resolve(body.get('data') as T)
- } else {
- const msg = body.getString('message') ?? '请求失败'
- uni.showToast({ title: msg, icon: 'none' })
- reject(new Error(msg))
- }
- } else {
- const msg = '网络错误 ' + statusCode
- uni.showToast({ title: msg, icon: 'none' })
- reject(new Error(msg))
- }
- },
- fail: (err) => {
- const msg = err.errMsg ?? '请求失败'
- uni.showToast({ title: msg, icon: 'none' })
- reject(new Error(msg))
- }
- })
- })
- }
- export function get<T>(url : string, data ?: UTSJSONObject | null) : Promise<T> {
- return request<T>({ url: url, method: 'GET', data: data })
- }
- export function post<T>(url : string, data ?: UTSJSONObject | null) : Promise<T> {
- return request<T>({ url: url, method: 'POST', data: data })
- }
|