版本号
"vue": "^3.2.45",
"axios": "^1.4.0",
"axios-miniprogram-adapter": "^0.3.5",
安装axios及axios适配器,适配小程序
yarn add axios axios-miniprogram-adapter
使用axios
在
utils
创建utils/request.ts
文件
import axios from "axios"
import type { AxiosAdapter, AxiosInstance, AxiosPromise, AxiosRequestConfig, AxiosResponse } from "axios";
import mpAdapter from "axios-miniprogram-adapter";
axios.defaults.adapter = mpAdapter as anyinterface Result<T = any> {code: number | string;msg: string;data: T;
};/* declare module 'axios' {//如遇到request()方法里的retuen报类型错误,放开这段注释采用这种形式定义返回类型,将上方的Result接口注释interface AxiosResponse<T = any> {code: number | string;msg: string;data: T;}type Result<T = any> = AxiosResponse<T>;
} */// 导出Request类,可以用来自定义传递配置来创建实例
class HttpRequest {baseURL: string;timeout: number;constructor() {this.baseURL = import.meta.env.VITE_BASE_URL;this.timeout = 60000}request<T = any>(options: AxiosRequestConfig): Promise<Result<T>> {// axios 实例const instance: AxiosInstance = axios.create()this.setInterceptors(instance)const opts = this.mergeOptions(options)return instance(opts)}get<T = any>(url: string, data?: any, outHeaders = {}): Promise<Result<T>> {return this.request<T>({method: 'get',url,params: { ...data }, // get参数可以直接展开headers: {}})}post<T = any>(url: string, body = {}, outHeaders = {}): Promise<Result<T>> {let data = {body,header: {}}return this.request<T>({method: 'post',url,data, // post要求必须传入data属性})}mergeOptions(options: AxiosRequestConfig) {//console.log('合并参数', options)return {baseURL: this.baseURL,timeout: this.timeout,...options}}// 设置拦截器setInterceptors(instance: AxiosInstance) {// 请求拦截器instance.interceptors.request.use((config) => {uni.showLoading({title: '加载中...',mask: true});// 一般会请求拦截里面加token,用于后端的验证/* const token = localStorage.getItem("token")config!.headers!.Authorization = tokenconfig.headers = Object.assign(config.headers, { ...config.headers, token }); */return config},(err: any) => {console.log(err, '请求拦截报错');uni.hideLoading();return Promise.reject(err);})// 响应拦截器instance.interceptors.response.use((res: AxiosResponse) => {//res为AxiosResponse类型,含有config\data\headers\request\status\statusText属性console.log(res);uni.hideLoading();let { status, data } = resif (status === 200) {// return Promise.resolve(data)return data} else {}},err => {console.log('axios报错', err)uni.hideLoading(); // 立即关闭加载框return Promise.reject(err)})}
}
// 默认导出Request实例
export default new HttpRequest()
在
src
目录下创建src/api/config
文件夹
config文件夹中创建home.ts文件,首页的接口都放在里面统一管理
export default {getHomeData: "/frontpage",
}
和
config
文件夹同级创建home.ts文件,统一管理请求接口的方法
import axios from '@/utils/request'
import home from './config/home'export const getHomeData = () => axios.get(home.getHomeData) //无参使用方式
export const getHomeData = options:any => axios.get(home.getHomeData, options) //有参使用方式 options参数可以自行统一定义
在页面中使用,home.vue文件
<template><view class="content"></view>
</template><script setup lang="ts">
import { onMounted, ref } from 'vue'
import { getHomeData } from '@/api/home'onMounted(() => {homeData()
})const homeData = async () => {const { data } = await getHomeData()console.log(data, '首页数据+++++++++')
}
</script><style lang="scss"></style>