Axios 的二次封装

1. 简单版本:

Axios 的二次封装_第1张图片
config.js

const devBaseURL = "https://httpbin.org";
const proBaseURL = "https://production.org";
export const BASE_URL = process.env.NODE_ENV === 'development' ? devBaseURL: proBaseURL;

export const TIMEOUT = 5000;

request.js

import axios from 'axios';

import { BASE_URL, TIMEOUT } from "./config";

const instance = axios.create({
  baseURL: BASE_URL,
  timeout: TIMEOUT
});

instance.interceptors.request.use(config => {
  // 1.发送网络请求时, 在界面的中间位置显示Loading的组件

  // 2.某一些请求要求用户必须携带token, 如果没有携带, 那么直接跳转到登录页面

  // 3.params/data序列化的操作
  console.log("请求被拦截");

  return config;
}, err => {

});

instance.interceptors.response.use(res => {
  return res.data;
}, err => {
  if (err && err.response) {
    switch (err.response.status) {
      case 400:
        console.log("请求错误");
        break;
      case 401:
        console.log("未授权访问");
        break;
      default:
        console.log("其他错误信息");
    }
  }
  return err;
});

export default instance;


2. 完善版本

Axios 的二次封装_第2张图片

config.js

const devBaseURL = "https://httpbin.org";
const proBaseURL = "https://production.org";
export const BASE_URL = process.env.NODE_ENV === 'development' ? devBaseURL: proBaseURL;

export const TIMEOUT = 5000;

request.js

import axios, { AxiosInstance } from 'axios'
import { message } from 'antd'
import qs from 'qs'

import { BASE_URL, TIMEOUT } from "./config";

import { showFullScreenLoading, tryHideFullScreenLoading, paramFilter } from './emun'


/**
 * 创建axios实例
 */

const instance = axios.create({
  timeout: TIMEOUT, // 超时时间
  baseURL: BASE_URL,
  headers: {
    'Content-Type': 'application/json'
  }
})

/**
 * 添加请求拦截
 */

instance.interceptors.request.use(
  config => {
    console.log('object', config)
    if (config.showLoading) {
      showFullScreenLoading()
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

/**
 * 响应拦截
 */

instance.interceptors.response.use(
  response => {
    if (response.config.showLoading) {
      tryHideFullScreenLoading()
    }
    return response
  },
  error => {
    tryHideFullScreenLoading()
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = '错误请求'
          break
        case 401:
          error.message = '未授权,请重新登录'
          break
        case 403:
          error.message = '拒绝访问'
          break
        case 404:
          error.message = '请求错误,未找到该资源'
          break
        case 405:
          error.message = '请求方法未允许'
          break
        case 408:
          error.message = '请求超时'
          break
        case 500:
          error.message = '服务器端出错'
          break
        case 501:
          error.message = '网络未实现'
          break
        case 502:
          error.message = '网络错误'
          break
        case 503:
          error.message = '服务不可用'
          break
        case 504:
          error.message = '网络超时'
          break
        case 505:
          error.message = 'http版本不支持该请求'
          break
        default:
          error.message = `连接错误${error.response.status}`
      }
    } else {
      error.message = '连接到服务器失败'
    }
    return Promise.reject(error.message)
  }
)

/**
 * get请求
 * @method get
 * @param {url, params, showLoading} 请求地址,请求参数,是否需要加载层
 */
const defaultConfig = { showLoading: true }

function get(url, params, showLoading, error) {
  params = paramFilter(params)
  return new Promise((resolve, reject) => {
    instance
      .get(url, { params, ...defaultConfig, ...showLoading })
      .then(res => {
        resolve(res)
      })
      .catch(err => {
        err = error ? error : err
        message.error(err, 1)
        reject(err)
      })
  })
}

/**
 * @method post
 * @param {url, params, config} 请求地址,请求参数,是否需要加载层
 */
function post(url, params, config, error) {
  const { headers } = config
  let param = ''
  if (headers && headers['Content-Type'] === 'application/x-www-form-urlencoded') {
    param = qs.stringify(paramFilter(params))
  } else {
    param = paramFilter(params)
  }
  return new Promise((resolve, reject) => {
    instance
      .post(url, param, { ...defaultConfig, ...config })
      .then(res => {
        resolve(res)
      })
      .catch(err => {
        err = error ? error : err
        message.error(err, 1)
        reject(err)
      })
  })
}

export default {
  get,
  post
}

service.js 传参调用

Source Code

你可能感兴趣的:(react.js,javascript,前端,axios)