封装element的API

import axios from 'axios'
import { Message } from 'element-ui'
// 用于处理对提交对象进行序列化
import qs from 'qs'
// create an axios instance
// process.env 指的是当前的运行环境 所对应的 配置文件
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    return res
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
/**
 * 合并get与post提交
 * @param {} config
 */

// {
//   url: '/api/leju/admin/product/list', // 相对路径
//   method: 'get',
//   data,
//   params: data
// }
function http(config) {
  // 动手脚
  if (config.method.toLowerCase() == 'post') {
    // qs系列化
    // https://www.npmjs.com/package/qs
    //  arrayFormat: 'repeat' 作用:  { a: ['b', 'c'] }  ==> 'a=b&a=c'
    //  allowDots: true  作用: { a: { b: { c: 'd', e: 'f' } } }  ==>  'a.b.c=d&a.b.e=f'
    config.data = qs.stringify(config.data, { arrayFormat: 'repeat', allowDots: true })
  } else {
    config.params = config.data
    // 如果确定请求体和url的参数不会同时使用  这里可以吧data删除
    config.data = ''
  }
  return service(config)
}
export default http

baseURL与proxy冲突,当出现跨域时,应该在vue.config.js中使用proxy拦截

  devServer: {
    port: port,
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    // 配置代理 解决跨域
    proxy: {
      // 拦截所有的包含'/admin' 的请求  把该请求 代理到 target的目标对象去  
      // key是可以通过正则 配置 拦截规则的 
      // 那么在目标对象的服务器时无法感知该请求实际上时一个跨域请求
      // 如果在vue.config.js中通过proxy配好置了跨域  那么在axios的封装中 就得去掉 baseUrl !!!
      // '^/' : {这个是拦截的地方
      '/api' : {
        target: `http://www.baidu.com`,  // http://www.baidu.com/admin/xxxxx
        changeOrigin: true,  // 是跨域了
        pathRewrite: {
          // ['^' + process.env.VUE_APP_BASE_API]: ''   作用: 可以实现比如请求时 abc/bf/getUserInfo ==> abc/tt/getUserInfo
        }
      },
    },
    // 干扰代码 实际开发 没有这个东西 讲完我会把没用的mock配置全删掉
    after: require('./mock/mock-server.js')
  },
原文地址:https://www.cnblogs.com/123poi/p/13215636.html