前言
在做vue中大型项目的时候,官方推荐使用axios,但是原生的axios可能对项目的适配不友好,所以,在工程开始的来时候来封装一下axios,保持全项目数据处理的统一性。此文主要讲在vue-cli项目中如何封装axios,封装请求,封装公共的api,页面如何调用请求。
正式配置路线:
- 拿到项目及后台接口,首先做的是配置全局代理及第二点。
- 全局封装axios及第三点request.js。
- 过滤axios请求方式,控制路径及参数的格式及第四点http.js。
- 正式封装api及第五点api.js。
- 页面调用。
复制代码
正文
一、VUE项目的前期配置
新建vue项目,下载axios,并在main.js中导入axios。
npm i axios -S
复制代码
// main.js
import axios from "axios"
复制代码
二、配置config文件中的代理地址
在项目config目录下的index.js文件,这里是主要书写配置多个后台接口。
vue cil2 旧版本的代理配置–confin/index.js
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
// 后端请求地址代理,配置后testIp再之后的页面调用时就直接指代 http://197.82.15.15:8088
proxyTable: {
'/testIp': {
target: 'http://197.82.15.15:8088',
changeOrigin: true,
pathRewrite: {
'^/testIp': ''
}
},
'/elseIp': {
target: 'http://182.83.19.15:8080',
changeOrigin: true,
pathRewrite: {
'^/esleIp': ''
}
},
},
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',
// 如果您在调试devtools中的vue文件时遇到问题,
// 将此设置为false ,他可能有所帮助
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
},
复制代码
vue cil 3+ 新版本的代理配置 vue.config.js 文件
关于多代理配置:
devServer: {
overlay: {
// 让浏览器 overlay 同时显示警告和错误
warnings: true,
errors: true
},
host: "localhost",
port: 8080, // 端口号
https: false, // https:{
type:Boolean}
open: false, //配置后自动启动浏览器
hotOnly: true, // 热更新
// proxy: 'http://localhost:8080' // 配置跨域处理,只有一个代理
proxy: {
//配置多个代理
"/testIp": {
target: "http://197.0.0.1:8088",
changeOrigin: true,
ws: true,//websocket支持
secure: false,
pathRewrite