Axios 二次封装

config.js

/**

* 环境配置

*/

const env = process.env.NODE_ENV

const EnvConfig = {

  development: {

    baseApi: '/api',

    mockApi: 'https://www.fastmock.site/mock/85a6a7c326e7e02cf212a5315e637e3b/api'

  },

  production: {

    baseApi: '//front.pc.com/api',

    mockApi: 'https://www.fastmock.site/mock/85a6a7c326e7e02cf212a5315e637e3b/api'

  }

}

export default {

  env: env,

  mock: true,

  namespace: 'front_pc',

  polyv: 'https://player.polyv.net/script/player.js',

  ...EnvConfig[env]

}

request.js

/**

* axios 二次封装

*/

import axios from "axios";

import config from '@/config'

import router from '@/router'

import qs from 'qs'

import storage from '@/utils/storage'

import { Loading, Message } from 'element-ui'

let loding = null

const NETWORK_ERROR = '网络请求异常,请稍后重试'

const TOKEN_INVALID = 'Token认证失败,请重新登录'

// 创建axios实例添加全局配置

const service = axios.create({

  baseURL: config.baseApi,

  timeout: 8000,

  headers: {

    "Content-Type": 'application/x-www-form-urlencoded;charset=utf8'

  }

})

// 请求拦截

service.interceptors.request.use((req) => {

  // TO-DO

  const headers = req.headers;

  // 是否需要加载中

  if (req.options.hasLoading) {

    loding = Loading.service({

      lock: true,

      text: 'Loading',

      spinner: 'el-icon-loading',

      background: 'rgba(0, 0, 0, 0.7)'

    })

  }

  // 是否需要token

  if (req.options.hasToken) {

    // token

    const { token } = storage.getItem('userInfo')

    headers.Authorization = 'Bearer ' + token

  }

  // if (!headers.Authorization) headers.Authorization = 'Bearer ' + token

  return req

})

// 响应拦截

service.interceptors.response.use((res) => {

  if (loding) {

    loding.close()

  }

  const { code, data, msg } = res.data

  if (code === 200) {

    msg && Message.success(msg)

    return data

  } else if (code == 50001) {

    Message.error(TOKEN_INVALID)

    setTimeout(() => {

      router.push('/')

    }, 1500)

    return Promise.reject(TOKEN_INVALID)

  } else {

    Message.error(msg || NETWORK_ERROR)

    return Promise.reject(msg || NETWORK_ERROR)

  }

})

/**

* 请求的核心函数

* @param {*} options 请求配置

*/

const request = (options) => {

  options.method = options.method || 'get'

  options.data = options.method === 'get' ? options.data : qs.stringify(options.data)

  if (options.method.toLowerCase() === 'get') {

    options.params = options.data

  }

  if (typeof options.mock != 'undefined') {

    config.mock = options.mock

  }

  if (config.env === 'production') {

    service.defaults.baseURL = config.baseApi

  } else {

    service.defaults.baseURL = config.mock ? config.mockApi : config.baseApi

  }

  return service(options)

}

['get', 'post', 'put', 'delete', 'patch'].forEach(item => {

  request[item] = (url, data, options) => {

    data = qs.stringify(data)

    return request({

      url,

      data,

      method: item,

      ...options

    })

  }

})

export default request

你可能感兴趣的:(Axios 二次封装)