uView2.0 对http进行封装

request.js:

// 此vm参数为页面的实例,可以通过它引用vuex中的变量
import { $config } from '@/config/config';
module.exports = (vm) => {
  // 初始化请求配置
  uni.$u.http.setConfig((config) => {
    /* config 为默认全局配置*/
    config.baseURL = $config.baseUrl; /* 根域名 */
    return config;
  });

  // 请求拦截
  uni.$u.http.interceptors.request.use(
    (config) => {
      // 可使用async await 做异步操作
      // 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
      config.data = config.data || {};
      // 根据custom参数中配置的是否需要token,添加对应的请求头
      if (config?.custom?.auth) {
        // 可以在此通过vm引用vuex中的变量,具体值在vm.$store.state中
        config.header.Authorization = vm.access_token;
      }
      return config;
    },
    (config) => {
      // 可使用async await 做异步操作
      return Promise.reject(config);
    }
  );

  // 响应拦截
  uni.$u.http.interceptors.response.use(
    (response) => {
      // statusCode为200的情况
      return response.data === undefined ? {} : response.data;
    },
    (response) => {
      // token验证失败
      const { status, msg, data } = response;
      // 自定义参数
      const custom = response.config?.custom;
      // 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
      if (custom.toast !== false) {
        uni.$u.toast(msg);
      }
      if (statusCode === 401) {
        setTimeout(() => {
          uni.$u.route('pages/login/login');
        }, 1500);
      }
      if (custom?.catch) {
        return Promise.reject(data);
      } else {
        // 否则返回一个pending中的promise,请求不会进入catch中
        return new Promise(() => {});
      }
    }
  );
};

  

在main.js中引入:

// 引入请求封装,将app参数传递到配置中
require('./config/request.js')(app);
app.$mount();

  

api.js使用:

const http = uni.$u.http;

// post请求
export const postMenu = (params, config = {}) => http.post('/ebapi/public_api/index', params, config);

// get请求,注意:get请求的配置等,都在第二个参数中
export const getMenu = (data) => http.get('/ebapi/public_api/index', data);

  

 

posted @ 2023-01-29 15:49  zaijinyang  阅读(381)  评论(0编辑  收藏  举报