Skip to content

Http请求

轻量级http请求工具,支持postgetputdelete四种基本请求方式。它不追求功能的全面覆盖,而是致力于简约高效,针对用户实际需求进行优化。我们的目标是让插件轻巧易用,让用户在第一时间享受到便捷的体验,真正实现一键启动,快速上手。

支持平台

AppH5微信小程序支付宝小程序百度小程序头条小程序QQ小程序
xxxx

创建 axios.uts

js
import config from '../config/config.uts'
import { TuiAxios } from '@/uni_modules/t-ui'
import { state } from '../store/user.uts'
const reqIns = new TuiAxios({
	baseURL: config.baseUrl,
	timeout: 6000,
	header: {
		'Content-Type': 'application/json',
		appid: config.appSelect
	}
})

reqIns.requestInterceptor = (config : Map<string, any>) => {
	const token = state.token
	const header = config.get('header') as UTSJSONObject
	header.set('token', token)
	config.set('header', header)
}

reqIns.responseInterceptor = (res : RequestSuccess<any>, resolve : (res : UTSJSONObject) => void, reject : (err : Error) => void) => {
	if (typeof (res.data) == 'string') {
		resolve({ data: res.data })
		return
	}
	const resp : UTSJSONObject = res.data as UTSJSONObject
	const code : Number = resp.getNumber('code') as number
	if (code == 0) {
		resolve(resp)
	} else {
		const message : string = resp.getString('message') as string
		reject(new Error(`${message}`))
	}
}

export default reqIns

使用方法

js
import axios from '../axios/axios.uts'

export function viteApi(path : string, data : any = {}) : Promise<UTSJSONObject> {
	return axios.post(path, data as UTSJSONObject)
}