封装Axios

时间:2024-03-15 18:58:27

1、安装axios插件

npm i axios

2、根据项目需求:比如一个项目使用多个后端服务 那么baseURL需要动态传入,或者不同的请求设置不同的请求头字段

src/utils/request.js

import axios from 'axios';

class Request {
  constructor(props) {
    this.init(props);
  }
  init(props) {
    let servicesParams = {
      baseURL:
        props && props.baseURL ? props.baseURL : process.env.VUE_APP_BASE_API,
      timeout: props && props.timeout ? props.timeout : 10000,
      // 跨域用   请求头带cookie
      withCredentials: props && props.withCredentials === false ? false : true,
      headers: {
        'Content-Type':
          props && props.ContentType
            ? props.ContentType
            : 'application/json;charset=utf-8',
        'uniplatform': props && props.uniplatform ? props.uniplatform : 'NBPT',
      },
    };
    // 创建axios实例
    const service = axios.create(servicesParams);
    service.interceptors.request.use(
      async function (request) {
        return request;
      },
      function (error) {
        return Promise.reject(error);
      }
    );
    service.interceptors.response.use(
      (response) => {
        if (response.status === 200) {
          return response.data;
        }
        Promise.reject();
      },
      (error) => {
        return Promise.reject(error);
      }
    );
    this.service = service;
  }
}
class RequestInit extends Request {
  init(props) {
    super.init(props);
    return this.service;
  }
}
const request = new Request().service;
const requestInit = new RequestInit();

export { request, requestInit };

3、使用举例

src/api/modules/detail.js

import { requestInit } from '@/utils/request.js';

let servicesRefParams = {
  baseURL: process.env.VUE_APP_BASE_NXGP_API,
  uniplatform: 'CREF',
};
let request1 = requestInit.init(servicesRefParams);

export function getRefReleased(val) {
  return request1({
    url: process.env.VUE_APP_VERSION + `/resources/released`,
    method: 'GET',
    headers: {
      version: val,
    },
  });
}

页面调用:

import { getRefReleased} from '@/api/modules/detail.js';

getRefReleased('xxx');