vue-cli3 配置axios跨域及封装

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

module.exports = {
  publicPath: './',
  outputDir: 'dist',
  lintOnSave: true,
  productionSourceMap: false,
  devServer: {
    host: '0.0.0.0',
    port:'8080',
    disableHostCheck: true,
    https:false,
    hotOnly: false,
    //代理
    proxy: {
      '/api': {
        target:'http://yapi.demo.qunar.com/mock/68531',
        changeOrigin: true,
        ws:true,
        //重写路径  需要设置重写的话,要在后面的调用接口前加上/api 来代替target
        pathRewrite:{
          // '^/api': ''
        }
      }
    }
  }
}

vue-cli3 配置axios跨域及封装_第1张图片
在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

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()
      }
    }
  }
}

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}
 */
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

在account.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)
}

你可能感兴趣的:(vue-cli3 配置axios跨域及封装)