直接上代码
首先封装一个共同的地址文件,通常命名config.js
// 开发环境配置
export let baseUrl;
export let version;
if (process.env.NODE_ENV === 'development') {
baseUrl = "http://192.168.10.154:8090/";
} else {
baseUrl = "http://192.168.10.154:8090/";
}
version ='v3.0.0';
if (typeof baseUrl === 'undefined') {
console.error('请检查.env配置文件是否存在');
} else {
console.log(`[ma ${version}] `);
}
export const apiPath = '/api/ops/';
export const staticUrl = '';
export default {
baseUrl,
apiPath,
staticUrl,
};
下面是封装的拦截器
一般情况下命名 request.js
import Request from 'luch-request';
import {
baseUrl,
apiPath
} from './config';
// 创建一个请求实例
const http = new Request({
baseURL: baseUrl,
timeout: 8000,
header: {
'Content-Type': 'application/json;charset=UTF-8',
},
});
// Loading全局实例
let loadingInstance = null;
// 显示loading
function showLoading(message = '加载中') {
if (!loadingInstance) {
loadingInstance = uni.showLoading({
title: message,
mask: true,
});
}
}
// 请求拦截器
http.interceptors.request.use(
(config) => {
const token = uni.getStorageSync('token');
if (token) {
config.header['token'] = token;
}
// 显示loading(可根据需要添加条件)
showLoading();
return config;
},
(error) => {
return Promise.reject(error);
}
);
// 响应拦截器
http.interceptors.response.use(
(response) => {
// 隐藏loading
uni.hideLoading()
// 假设服务器返回的数据格式包含{code, data, msg}
if (response.data.code !== 200) {
// 显示错误信息(可根据需要自定义)
uni.showToast({
title: response.data.msg || '请求失败,请稍后再试',
icon: 'none',
});
return Promise.reject(response.data);
}
return Promise.resolve(response.data);
},
(error) => {
// 隐藏loading(确保无论成功还是失败都隐藏loading)
uni.hideLoading()
// 显示通用错误信息(可根据需要自定义)
uni.showToast({
title: '网络请求出错,请检查您的网络连接',
icon: 'none',
});
return Promise.reject(error);
}
);
// 封装请求函数
const request = (config) => {
// 确保URL以斜杠开头(如果不是以apiPath作为前缀)
if (config.url && config.url[0] !== '/') {
config.url = apiPath + config.url;
}
return http.middleware(config);
};
export default request;
luch-request 下载一下即可
下面便是使用示例了
// 引入封装好的request函数
import request from '@/utils/request.js'; // 根据你的文件路径调整
import {
baseUrl
} from '../config';
// 换电站 列表
export const getDataList = (data) => {
return request({
url: 'station/getSummaryInfo',
method: 'GET',
data: {
...data,
},
custom: {
showError: false,
showLoading: false,
},
})
}
// 换电站 获取详情
export const getDetail = (data) => {
return request({
url: `station/getDetail`,
method: 'GET',
data: {
...data,
},
custom: {
showError: false,
showLoading: false,
},
})
}