个人完整 axios 配置

新建一个文件夹 专门管理 axios 的全局默认配置 config.js 项如下:
下面的 baseUrl 可在 .env.production.env.development 加对应参数,然后使用 process.env.baseUrl
需要特别注意的是 .env.production.env.development文件 参数说明:

  • NODE_ENV - 是 “development”、“production” 、”test”或者自定义的值。具体的值取决于应用运行的模式
  • BASE_URL - 会和 vue.config.js 中的 publicPath 选项相符,即你的应用会部署到的基础路径
  • 除了 NODEENV 和 BASE_URL,其他的环境变量必须以 VUE_APP 开头
  • 项目中使用:process.env.环境变量名,eg:VUE_APP_BASE_URL ```javascript import axios from ‘axios’ import qs from ‘qs’ import router from ‘@/router’ import config from ‘./config’

axios.defaults.timeout = config.timeout axios.defaults.headers = config.headers axios.defaults.baseURL = config.baseURL

// 请求拦截器 axios.interceptors.request.use( (config) => { // 触发loading效果 //判断是否存在token,如果存在,则在header上加上token // let token = getStore(‘token’) // if (token) { // config.headers.common[‘token’] = token // } // if (config.method == ‘post’ || config.method == ‘put’) { // //将数据转成string // config.data = JSON.stringify(config.data) // } else if (config.method == ‘get’) { // //&& browser.isIE // //给Get添加时间戳 解决IE缓存问题 // let symbol = config.url.indexOf(‘?’) >= 0 ? ‘&’ : ‘?’ // config.url += symbol + ‘_=’ + Date.now() // config.data = qs.stringify(config.data) // } return config }, (err) => { // 关闭loading // 失败提示 return Promise.resolve(err) } )

// 响应拦截器 axios.interceptors.response.use( (response) => { // 关闭loading if (!response || !response.data || !response.data.success) { // 失败提示 } else if (response.data.data && response.data.code == 200) { // 成功处理 } if (response.data) { switch (response.data.code) { case 401: // 返回 401 清除token信息并跳转到登录页面 // store.commit(‘LOGOUT’) setTimeout(function () { router.replace({ path: ‘/login’, // 登录成功后跳入浏览的当前页面 // query: {redirect: router.currentRoute.fullPath} }) }, 1500) break case 402: //402无权限操作 // 提示 return new Promise(() => {}) //外部不会再处理 break } } return response }, (err) => { // 关闭loading // 提示异常 // return Promise.resolve(err); //外部不会再处理 return new Promise(() => {}) } ) export default { Get(url, params = {}) { return new Promise((resolve, reject) => { axios .get(url, { params }) .then((res) => { resolve(res.data) }) .catch((error) => { reject(error) //resolve(error) }) }) }, Post(url, params = {}) { return new Promise((resolve, reject) => { axios .post(url, params) .then((res) => { resolve(res.data) }) .catch((error) => { reject(error) //resolve(error) }) }) }, Delete(url, params = {}) { return new Promise((resolve, reject) => { axios .delete(url, params) .then((res) => { resolve(res.data) }) .catch((error) => { reject(error) //resolve(error) }) }) }, Put(url, params = {}) { return new Promise((resolve, reject) => { axios .put(url, params) .then((res) => { resolve(res.data) }) .catch((error) => { reject(error) //resolve(error) }) }) }, } ``` 1