vue搭建项目(一):axios的使用

一、项目使用axios
1.安装axios

npm install --save axios

2.axios二次封装
对axios进行二次封装主要是为了设置请求拦截器(在请求发出之前做一些事情)和响应拦截器(在数据返回之后,做一些事情)
2.1.src下创建一个文件夹专门用来装所有请求的js文件 src/api/request.js
request.js

//对于axios进行二次封装
import axios from "axios";
//底下的代码也是创建axios实例
let requests = axios.create({
    
    
  //基础路径
  baseURL: "/local",//对应vue.config文件里面的proxy代理
  //请求不能超过5S
  timeout: 5000,
});
 
//请求拦截器(可以在请求发出去之前,做一些事情)
requests.interceptors.request.use((config) => {
    
    
config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  return config;
}, error => {
    
    
  Promise.reject(error)
}))
 
//响应拦截器(在数据返回之后,做一些事情)
requests.interceptors.response.use(
  (res) => {
    
    
    //响应成功
    return res.data;
  },
  (err) => {
    
    
    //响应失败
    alert("服务器响应数据失败");
  }
);
export default requests;

3.配置代理服务器:在vue.config中配置(devServer.proxy部分)
vue.config 完整配置参考文档最下面链接


const CompressionPlugin = require('compression-webpack-plugin')

const name =  '配电监测' // 网页标题

// vue.config.js 配置说明
//官方vue.config.js 参考文档 https://cli.vuejs.org/zh/config/#css-loaderoptions
// 这里只列一部分,具体配置参考文档
module.exports = {
    
    
  // 部署生产环境和开发环境下的URL。
  // 默认情况下,Vue CLI 会假设你的应用是被部署在一个域名的根路径上
  // 例如 https://www.ruoyi.vip/。如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在 https://www.ruoyi.vip/admin/,则设置 baseUrl 为 /admin/。
  // publicPath: process.env.NODE_ENV === "production" ? "/" : "/",
  // 在npm run build 或 yarn build 时 ,生成文件的目录名称(要和baseUrl的生产环境路径一致)(默认dist)
  outputDir: 'dist',
  // 用于放置生成的静态资源 (js、css、img、fonts) 的;(项目打包之后,静态资源会放在这个文件夹下)
  assetsDir: 'static',
  // 是否开启eslint保存检测,有效值:ture | false | 'error'
  // lintOnSave: process.env.NODE_ENV === 'development',
  lintOnSave: false,
  // 如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。
  productionSourceMap: false,
  // webpack-dev-server 相关配置
  devServer: {
    
    
    host: '0.0.0.0',//指定使用的ip地址,默认为localhost,如果使用'0.0.0.0'则可以被外部访问
    port: '8080',
    open: true,
    proxy: {
    
    
      // detail: https://cli.vuejs.org/config/#devserver-proxy
      'local': {
    
    
         target: `http://10.100.10.54:18080`,//测试服
        //target: `https://icp.minexiot.com/prod-api`,//正式服
        // target: `http://172.16.201.59:18080`,
        changeOrigin: true,
       // pathRewrite: {
    
    
       //  ['^' + process.env.VUE_APP_BASE_API]: ''
       // }
      }
    },
    disableHostCheck: true
  },
  css: {
    
    
    loaderOptions: {
    
    
      sass: {
    
    
        sassOptions: {
    
     outputStyle: "expanded" }
      }
    }
  },
  configureWebpack: {
    
    
    name: name,
    resolve: {
    
    
      alias: {
    
    
       '@': path.resolve(__dirname, 'src')
      }
    },
    plugins: [
      // http://doc.ruoyi.vip/ruoyi-vue/other/faq.html#使用gzip解压缩静态文件
      new CompressionPlugin({
    
    
        cache: false,                   // 不启用文件缓存
        test: /\.(js|css|html)?$/i,     // 压缩文件格式
        filename: '[path].gz[query]',   // 压缩后的文件名
        algorithm: 'gzip',              // 使用gzip压缩
        minRatio: 0.8                   // 压缩率小于1才会压缩
      })
    ],
  },
  chainWebpack (config) {
    
    
    config.plugins.delete('preload') // TODO: need test
    config.plugins.delete('prefetch') // TODO: need test

    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/assets/icons'))
      .end()
        }
      )
  }
}

4.使用
在api文件下创建一个新的文件夹方便管理接口 src/api/common/index.js

import request from '@/api/request' 

// 获取所有下拉菜单type
export const getType = () => {
    
    
  return request({
    
    
    url: '/selects/types',
    method: 'get',
  })
}

// 根据type获取下拉列表数据
export const getTypeOption = (type) => {
    
    
  return request({
    
    
    url: '/selects',
    method: 'get',
    params: {
    
    type:type}
  })
}

vue页面使用:

import {
    
     getTypeOption } from "@/api/common/index";//引入

getTypeOptions() {
    
    
      getTypeOption("OperationAction").then((res) => {
    
    
        if (res.code == 200) {
    
    
          //成功操作
        }
      });
    },

参考/其他:
VUE项目中引入axios
VUE中axios的使用
Vue.conifg.js完整配置项
Vue项目中svg的使用

猜你喜欢

转载自blog.csdn.net/Web_Notes/article/details/131223783