vue axios的封装

在根目录上创建一个vue.config.js文件

const path = require("path");
const resolve = function(dir) {
    return path.join(__dirname, dir);
};
module.exports = {
    publicPath: "./",
    outputDir: "dist",
    assetsDir: "static",
    lintOnSave: false, // 是否开启eslint保存检测
    productionSourceMap: false, // 是否在构建生产包时生成sourcdeMap
    chainWebpack: config => {
        config.resolve.alias
            .set("@", resolve("src"))
            .set("@", resolve("src/views"))
            .set("@", resolve("src/components"))
            .set("@", resolve("src/common"))
            .set("@", resolve("src/utils"))
            .set("@", resolve("src/service")); /* 别名配置 */
        config.optimization.runtimeChunk("single");
    },
    devServer: {
        // host: "localhost",
        /* 本地ip地址 */
        host: "localhost",
        port: "10000",
        hot: true,
        /* 自动打开浏览器 */
        open: true,
        overlay: {
            warning: false,
            error: true
        },
        /* 跨域代理 */
        proxy: {
            "/item": {
                /* 目标代理服务器地址 */
                target: "http://localhost:80", //localhost:80/api/item/category/list
                /* 允许跨域 */
                changeOrigin: true,
                ws: true,
                pathRewrite: {
                    "^/item": ""
                }
            }
        }
    }
};

  vue axios的封装

 

 在api.js里面配置

import Vue from ‘vue‘
import modules from ‘@/api‘

const api = {
//实例化axios  用$api代替
  install(Vue) {
    Vue.prototype.$api = modules
    Vue.$api = modules
  },
  $api: modules
}

Vue.use(api)

  在axios.js

import axios from ‘axios‘
import printLog from ‘./log‘

//创建axios实例
const fetch = axios.create({
  baseURL:‘/api‘,
  timeout: 15000
})

// 修改 axios 实例默认配置
fetch.defaults.headers.post[‘Content-Type‘] = ‘application/json‘
fetch.defaults.headers.put[‘Content-Type‘] = ‘application/json‘
fetch.defaults.headers.patch[‘Content-Type‘] = ‘application/json‘

//request拦截器
fetch.interceptors.request.use(
  config =>{
    if (config.method === ‘get‘) {
      if (config.params === undefined) {
        config.params = {}
      }
      config.params = {
        ...config.params,
        ...(config.params.filter
          ? {
          filter: JSON.stringify(config.params.filter)
          }
          :{})
      }
    }
    printLog({ config })
    return config
  },
  error =>{
    //网络没建立成功
   window.console.error(error)
    return Promise.reject(error)
  }
)

//response拦截器
fetch.interceptors.response.use(
  response =>{
    printLog({ response })
    if (response.status === 200) {
      return checkResponseCode(response)
    } else {
      //window.console.log(response)
    }
  },
  error => {
    //后台服务异常  404 504 请求超时等
    //window.console.err(error, error.response, error.message)
    return Promise.reject(error.response)
  }
)

const checkResponseCode = response => {
 switch (response.data.code) {
   case 0:
     return Promise.reject(response.data)

   case 404:
     return Promise.reject(response.data)
 }
}

export default fetch

  request.js

import axios from ‘axios‘
//创建axios实例
const service = axios.create({
  baseURL: ‘/api‘,
  timeout: 15000 //请求超出时间
})

//请求拦截
service.interceptors.request.use(
  config => {
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

//响应拦截
service.interceptors.response.use(
  response=>{
    const { code, msg, data } = response.data
    if (code === 0) {
      return data
    } else {
      return promptError(code,msg,response.data)
    }
  },
  error => {
    const { status, statusText, data } = error.response
    return promptError(status, data.msg || statusText, error.response)

  }
)

/**
 * 提示错误
 * @param CODE 错误码
 * @param MSG 错误提示
 * @param REJECT reject 内容
 * @returns {Promise<never>}
 */
const promptError = (CODE, MSG, REJECT) => {
  //错误描述
  return Promise.reject(REJECT)
}
export { service as axios}

在api文件夹下的index.js

const files = require.context(‘.‘, false, /\.js$/)
let modules = {}

files.keys().forEach(key => {
  if (key === ‘./index.js‘) return
  modules = { ...modules, ...files(key) }
})

export default modules

 在user.js封装统一的请求 

import { axios } from ‘@/utils/axios/request‘

//登录
export const login = data => {
  return axios.post(‘/v1/user/login‘, data)
}
  //如果配置了 pathRewrite 需要在路径之前加上重写的
  /*
例
 pathRewrite:{
           ‘^/api‘: ‘‘
        }

这里的请求就需要写成
export const login = data => {
  return axios.post(‘/api/v1/user/login‘, data)
}
*/
//注册
export const register = data => {
  return axios.post(‘/v1/user/register‘, data)
}

//提交信息采集表
export const enrollment = data => {
  return axios.post(‘/v1/enrollment/post‘, data)
}

  log.js

export default ({ config, response }) => {
  const debug = true
  if (debug) {
    // 请求
    if (config) {
      window.console.groupCollapsed(`%c[${config.method}]`, ‘color:#ffb400‘, config.baseURL + config.url)
      // console.log(‘%c[Content-Type]‘, ‘color:#ffb400‘, config.method, config.headers[config.method][‘Content-Type‘])
      // console.log(‘%c[X-Access-Token]‘, ‘color:#ffb400‘, config.headers[‘X-Access-Token‘])
      if (config.method === ‘get‘ || config.method === ‘delete‘) {
        window.console.log(‘%c[params]‘, ‘color:#ffb400‘, config.params)
      } else {
        window.console.log(‘%c[data]‘, ‘color:#ffb400‘, config.data)
      }
      window.console.dir(config)
      window.console.groupEnd()
    }

    // 响应
    if (response) {
      if (response.data.code === 0) {
      window.console.groupCollapsed(`%c[响应成功]`, ‘color:#27ae60‘, response.config.url)
      window.console.log(‘%c[data]‘, ‘color:#ffb400‘, response.data.data)
      window.console.dir(response.data)
      window.console.groupEnd()
      } else {
      window.console.group(`%c[响应错误]`, ‘color:#e1514c‘, response.config.url)
      window.console.log(‘%c[code]‘, ‘color:#e1514c‘, response.data.code)
      window.console.log(‘%c[msg]‘, ‘color:#e1514c‘, response.data.msg)
      window.console.groupEnd()
      }
    }
  }
}

  

非常感谢https://me.csdn.net/weixin_43893437对我的帮助。

vue axios的封装

上一篇:【转】Android Studio 如何导出和导入设置


下一篇:vue路由和axios插件安装