目录
前言
在做vue中大型项目的时候,官方推荐使用axios,但是原生的axios可能对项目的适配不友好,所以,在工程开始的来封装一下axios,保持全项目数据处理的统一性。此文主要讲在vue-cil项目中如何封装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文件,这里是主要书写配置多个后台接口。关于代理可能出现的问题,可以查看我的另一篇文档VueCil代理本地proxytable报错的解析;
tips:如果报错服务器连接失败,是因为下面配置的代理地址是错误的,是我写的假的,需要替换成自己的服务器ip端口!!! error.message = ‘连接服务器失败’!
vue cil2旧版本的代理配置——config/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',
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
},
vuecil 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: {
"^/testIp": "/"
}
},
"/elseIp": {
target: "http://197.0.0.2:8088",
changeOrigin: true,
//ws: true,//websocket支持
secure: false,