记录一下通用的Vue项目超简单整合Axios,复制粘贴代码后npm run serve或npm start,如控制台提示缺少依赖包,npm导入一下即可。

src/api/request.js

import axios from 'axios';
// import Nprogress from 'nprogress'
// import 'nprogress/nprogress.css'
import { ElMessage } from 'element-plus'

/**
 * 注意:
 * 由于项目部署到 Nginx 反向代理服务器,Nginx 默认超时时间为 60秒 * 2 (即 proxy_connect_timeout 默认超时时间的 60 秒 + proxy_read_timeout 默认超时时间的 60 秒),
 * 因此需要设置 Nginx 的 proxy_connect_timeout 和 proxy_read_timeout 超时配置,axios 的 timeout 才可起作用。
 * 另外,proxy_connect_timeout 不能超过 75 秒,此配置不是等待后端返回页面的时间,而 proxy_read_timeout 才是声明等待后端返回页面的时间的配置。
 */
const http = axios.create({
  baseURL: '/loveProject/api/',
  timeout: 3800 * 1000,
})

const NETWORK_ERROR = '网络错误,请联系开发人员'

/**
 * 请求拦截器
 */
http.interceptors.request.use((req) => {
  console.log('请求拦截器 =>', req)
  Nprogress.start()
  return req;
}, (error) => {
  Nprogress.done()
  return Promise.reject(error);
});

/**
 * 响应拦截器
 */
http.interceptors.response.use(function (res) {
  console.log('响应拦截器 =>', res)
  Nprogress.done()
  const {code, data, msg} = res.data
  if (code == 200) {
    return data
  } else {
    ElMessage.error((msg || NETWORK_ERROR))
    return Promise.reject(msg || NETWORK_ERROR)
  }
});

export default http

src/api/User/index.js

import http from '../request'

export default {
  /**
   * 根据userId查询用户
   * @param {*} userId 
   * @returns 
   */ 
  getUserById(userId) {
    return http.get(`https://***.com/zhiquan181/api/getUserById?userId=${userId}`)
  },

  /**
   * 查询所有用户
   * @returns 
   */ 
  getUsers() {
    return http.get(`/getUsers`)
  },

  /**
   * 保存用户信息
   * @param {*} data 
   * @returns 
   */
  saveJobRerunInfo(data) {
    return http({
      method: "POST",
      url: `https://***.com/zhiquan181/api/saveUserInfo`,
      headers: {
        "Content-Type": "application/json"
      },
      data
    })
  }
}

src/api/index.js

import Vue from 'vue'
import userApi from './User/index'
import axios from 'axios'

Vue.prototype.$http = {
  ...userApi,
}

Vue.prototype.$axios = axios

src/main.js

import Vue from 'vue'
import App from './App.vue'
import './utils/elementui'
import router from './router'
import store from './store'
import './api/index'
import './assets/less/public.css'
import './utils/moment'
import './assets/theme/index.css'
import moment from 'moment'
Vue.config.productionTip = false
Vue.prototype.$moment = moment;

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

vue.config.js

const CompressionPlugin = require('compression-webpack-plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const vConsolePlugin = require('vconsole-webpack-plugin')

module.exports = {
  outputDir: "static",// 定义打包目录,全局可访问
  publicPath: "/zhiquan181",// 定义公共地址,全局可访问
  lintOnSave: true,
  productionSourceMap: false,
  configureWebpack: (config) => {
    config.externals = {
      'vue': 'Vue',
      'element-ui': 'ELEMENT',
      'vue-router': 'VueRouter',
      'vuex': 'Vuex',
      'axios': 'axios',
      "moment": "moment"
    }

    /**
     * 压缩模块,针对于生产环境
     */
    const pluginsPro = [
      new CompressionPlugin({ // 文件开启Gzip,也可以通过服务端(如:nginx)
        filename: '[path].gz[query]',
        algorithm: 'gzip',
        test: new RegExp('\\.(' + ['js', 'css'].join('|') + ')$'),
        threshold: 10240,// 对超过10k的数据压缩
        minRatio: 0.8// 只有压缩率小于这个值的资源才会被处理
      }),
      new BundleAnalyzerPlugin()
    ];

    /**
     * 调试模块,针对于开发环境
     */
    const pluginsDev = [
      new vConsolePlugin({
        filter: [], // 需要过滤的入口文件
        enable: false // 发布代码前记得改回 false
      })
    ];
    
    if (process.env.NODE_ENV === 'production') {
      // 生产环境,启用压缩
      config.plugins = [...config.plugins, ...pluginsPro];
    } else {
      // 开发环境,启用调试
      config.plugins = [...config.plugins, ...pluginsDev];
    }
  },
  devServer: {
    open: true,
    overlay: {
      warnings: false,
      errors: true
    },
    hotOnly: false,
    proxy: {
      "/": {
        target: 'http://0.0.0.0:8080/',// 服务器地址
        changeOrigin: true,
        secure: false,
        ws: true
      }
    }
  }
}

src/view/App.vue

created() {
    this.getUserById(10001);
},
methods: {
    async getUserById(userId) {
        const res = await this.$http.getUserById(userId);
        if (res.success) {
            this.$message({
              message: res.msg,
              type: "success",
            });
        } else {
            this.$message({
              message: res.msg,
              type: "warning",
            });
        }
    }
}

顺便附上单独使用Axios的 Get 和 Post 两种方式

// get
axios.get(
  url, 
  {
    params:{},
    headers : {
      'auth-token': sessionStorage.getItem('auth-token')
    }
  }
)
.then((res) => {
  console.log('get =>', res);
}).catch(err =>{
  console.error(err)
})

// post
axios.post(
  url,
  data,
  {
    headers: {
      'Content-Type': 'application/json',
    },
  }
)
.then((res) => {
  console.log('post =>', res)
}).catch(err =>{
  console.error(err)
})

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐