由于小程序中的请求不是非常好用,没有axios好用,所以按照axios封装了一个简易的请求工具。
axiosWechat.js文件
class AxiosWechat {constructor(config = {}) {// 设置基础配置this.config = {baseUrl: '', // 基础路径headers: {}, // 请求头...config, // 合并用户传入的配置};// 初始化请求和响应拦截器数组this.requestInterceptors = [];this.responseInterceptors = [];}// 添加请求拦截器beforeRequest(fulfilled, rejected) {this.requestInterceptors.push({ fulfilled, rejected });}// 添加响应拦截器afterRequest(fulfilled, rejected) {this.responseInterceptors.push({ fulfilled, rejected });}// 通用请求方法request(config) {// 合并默认配置和请求配置config = { ...this.config, ...config };// 合并请求头config.headers = { ...this.config.headers, ...config.headers };let chain = Promise.resolve(config);// 执行请求拦截器this.requestInterceptors.forEach((interceptor) => {chain = chain.then(interceptor.fulfilled, interceptor.rejected);});// 发起请求chain = chain.then((finalConfig) => this._sendRequest(finalConfig));// 执行响应拦截器this.responseInterceptors.forEach((interceptor) => {chain = chain.then(interceptor.fulfilled, interceptor.rejected);});return chain;}// GET 请求方法get(url, params = {}, config = {}) {return this.request({url,method: 'GET',params, // GET 请求使用 params...config,});}// POST 请求方法post(url, data = {}, config = {}) {return this.request({url,method: 'POST',data, // POST 请求使用 data...config,});}// PUT 请求方法put(url, data = {}, config = {}) {return this.request({url,method: 'PUT',data, // PUT 请求使用 data...config,});}// DELETE 请求方法delete(url, params = {}, config = {}) {return this.request({url,method: 'DELETE',params, // DELETE 请求使用 params...config,});}// 内部请求处理_sendRequest(config) {return new Promise((resolve, reject) => {const { baseUrl, url, method, data, params, headers } = config;let weixin = wx;if (typeof uni !== 'undefined') {weixin = uni;}// 发送请求weixin.request({url: baseUrl + url,method: method || 'GET',data: method === 'GET' || method === 'DELETE' ? params : data, // GET 和 DELETE 使用 params,其他使用 dataheader: headers,success: resolve,fail: reject,});});} }export default AxiosWechat;
初始化请求工具
index.js
import axiosWechat from './axiosWechat.js'const $http = new axiosWechat({baseUrl: 'https://xxxxxx',headers: { 'Content-Type': 'application/json;charset=UTF-8' }, });// 请求拦截器 $http.beforeRequest((config) => {// 请求之前做需要做的return config;},(error) => {console.error('Request Interceptor Error:', error);return Promise.reject(error);} );// 响应拦截器 $http.afterRequest((response) => {// 请求回来需要做的return response.data}},(error) => {console.error('Response Interceptor Error:', error);return Promise.reject(error);} );export default $http
文件中使用
import axios from './index.js' const base = "/api/ofa-admin"export const login = (data) =>{// console.log(axios.post)return axios.post( `${base}/login`, data, { headers: { ... } }) }export const reqGetCodeImg = () =>{return axios.get( `${base}/open-api/captcha`) }