Newer
Older
KaiFengWechat / src / utils / request.js
@鲁yixuan 鲁yixuan on 12 Jul 2 KB update
import axios from 'axios';
import { showFailToast } from 'vant';
import { useStore } from '@/pinia/store.js';
import router from '@/router/index';
import { tansParams } from '@/utils/compatible.js';

const pinias = useStore();

// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项,表示请求URL公共部分
  baseURL: import.meta.env.VITE_APP_BASE_API,
  // 超时
  timeout: 30000,
});
//http request 拦截器
service.interceptors.request.use(
  (config) => {
    // 配置请求头
    config.headers = {
      'Content-Type': 'application/json;charset=UTF-8',
      Authorization: 'Bearer ' + localStorage.getItem('NFAppToken'),
    };
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

//http response 拦截器
service.interceptors.response.use(
  (response) => {
    // console.log('request success', response);
    const { code } = response ? response.data : 'undefined' || '';
    if (code == 401) {
      // showFailToast('登录已过期,请重新登录!');
      if (import.meta.env.MODE == 'development') {
        router.push('/login');
      } else {
        // window.location.href = 'http://192.168.16.94:8082/appMain/login'; //研发服务器
        window.location.href = 'https://server1.wh-nf.cn:8876/appMain/login'; //正式环境
      }
      return;
    }
    // axios单独请求接口时,未返回code情况处理
    if (code == undefined) {
      return response;
    }
    // 接口未返回数据时
    if (!!!code) {
      // showFailToast('数据请求失败,请稍后再试!');
      pinias.hideLoading();
      return false;
    }

    if (code != 200) {
      // showFailToast(response.data.message || response.data.msg || '');
    }
    return response;
  },
  (error) => {
    console.log('request error:', error);
    pinias.hideLoading();
    // showFailToast('网络连接异常,请稍后再试!');
  }
);

// 封装 GET POST 请求并导出
export default function request(config) {
  // get请求映射params参数
  if (config.params) {
    let url = config.url + '?' + tansParams(config.params);
    url = url.slice(0, -1);
    config.url = url;
  }
  const baseURL = import.meta.env.MODE == 'development' ? config.url : '/prod-api' + config.url;
  return new Promise((resolve, reject) => {
    let promise = axios({
      method: config.method,
      url: baseURL,
      data: config.data,
      header: config.header || {},
      dataType: 'json',
      timeout: config.timeout || 8000,
    });
    //处理返回
    promise
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}