vue axios package

Create a file on the root 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, // whether to open eslint save test
    productionSourceMap: false, // if sourcdeMap generated when constructing the package production
    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")); / * * alias configuration /
        config.optimization.runtimeChunk("single");
    },
    devServer: {
        // host: "localhost",
        / * Local ip address * /
        host: "localhost",
        port: "10000",
        hot: true,
        / * Automatically open the browser * /
        open: true,
        overlay: {
            warning: false,
            error: true
        },
        / * * Cross-Domain Proxy /
        proxy: {
            "/item": {
                / * Target proxy server address * /
                target: "http://localhost:80", //localhost:80/api/item/category/list
                / * Allow cross-domain * /
                changeOrigin: true,
                ws: true,
                Pthriawrite: {
                    "^/item": ""
                }
            }
        }
    }
};

  

 

 In the configuration inside api.js

Import view from 'View'
import modules from '@/api'

const api = {
// instantiate API axios substituting $
  install(Vue) {
    Vue.prototype.$api = modules
    Vue.$api = modules
  },
  $api: modules
}

Now e.use (What)

  In axios.js

import axios from 'axios'
import printLog from './log'

// Create instance axios
const fetch = axios.create({
  baseURL: '/' fire,
  timeout: 15000
})

// modify the default configuration examples 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 interceptor
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 =>{
    // not build a successful network
   window.console.error(error)
    return Promise.reject(error)
  }
)

// response interceptor
fetch.interceptors.response.use(
  response =>{
    printLog({ response })
    if (response.status === 200) {
      return checkResponseCode(response)
    } else {
      //window.console.log(response)
    }
  },
  error => {
    // background service request timeout abnormal 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 'Axios' from
 // Create instance Axios 
const -Service = axios.create ({
  baseURL: '/' fire ,
  timeout: 15000 // request time exceeds 
})

// request interception 
service.interceptors.request.use (
  config => {
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interception 
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)

  }
)

/**
 * An error
 * @Param CODE error code
 * @Param the MSG error
 * @Param REJECT Reject content
 * @returns {Promise<never>}
 * / 
Const promptError = (CODE, the MSG, REJECT) => {
   // an error description 
  return Promise.reject (REJECT)
}
export { service as axios}

index.js in the api folder

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

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

export default modules

 In a unified package request user.js 

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

//log in
export const login = data => {
  return axios.post('/v1/user/login', data)
}
  // If you configure pathRewrite need to add the path before rewriting
  /*
Case
 Pthriawrite: {
           '^/api': ''
        }

The request needs to be written here
export const login = data => {
  return axios.post('/api/v1/user/login', data)
}
*/
//registered
export const register = data => {
  return axios.post('/v1/user/register', data)
}

// submit information collection form
export const enrollment = data => {
  return axios.post('/v1/enrollment/post', data)
}

  log.js

export default ({ config, response }) => {
  const debug = true
  if (debug) {
    // request
    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()
    }

    // response
    if (response) {
      if (response.data.code === 0) {
      window.console.groupCollapsed ( `% c [success response]`, '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 [Error response]`, '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()
      }
    }
  }
}

  

Thank you very much https://me.csdn.net/weixin_43893437 help me.

Guess you like

Origin www.cnblogs.com/yscec/p/12114011.html