| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- // 基础配置
- const BASE_URL = process.env.VUE_APP_BASE_URL || 'https://esos-iot.bjdexn.cn'; // 从环境变量中获取 BASE_URL
- const TIMEOUT = 100000; // 请求超时时间
-
- // 请求拦截器
- const requestInterceptor = (config) => {
- // 在请求发送前处理
-
- config = {
- ...config,
- withCredentials: true,
- }
- // console.log('请求拦截器:', config);
- return config;
- };
-
- // 响应拦截器
- const responseInterceptor = (response) => {
- // 在响应返回后处理
- // console.log('响应拦截器:', response);
-
- // 处理响应数据statusCode
- if (response.statusCode === 200) {
- return response.data;
- } else {
- return Promise.reject(response.data);
- }
- };
-
- // 错误处理
- const errorHandler = (error) => {
- uni.reLaunch({
- url:'/pages/login/index'
- })
- console.error('请求失败:', error);
- // document.cookie = "rememberMe=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/user/;";
- // 统一处理错误
- if (error.errMsg) {
- uni.showToast({
- title: error.errMsg,
- icon: 'none',
- });
- }
-
- return Promise.reject(error);
- };
-
- // 封装请求方法
- const request = (options) => {
- // 合并配置
- // console.log(BASE_URL);
- // console.log(`${BASE_URL}${options.url}`);
- const config = {
- url: `${BASE_URL}${options.url}`,
- method: options.method || 'GET',
- header: options.header|| {},
- data: options.data || {},
- timeout: TIMEOUT,
- withCredentials: true
- // ...options,
- };
- // console.log(config);
- // 请求拦截器
- const finalConfig = requestInterceptor(config);
-
- // 返回 Promise
- return new Promise((resolve, reject) => {
- uni.request({
- ...finalConfig,
- success: (response) => {
- // 响应拦截器
- const data = responseInterceptor(response);
- // console.log(data);
- resolve(data);
- },
- fail: (error) => {
- // 错误处理
- errorHandler(error);
- reject(error);
- },
- });
- });
- };
-
- // 导出请求方法
- export default request;
|