前言
因为遇到了个配合多种后端语言的项目,所以有了这篇文章……
一、dev,prod环境,端口配置
3.0版本没config和dev.evn.js文件惹,咋整
1. 根目录下新建文件.env.dev
NODE_ENV = 'development'
VUE_APP_PHP_URL = '/aa' //请求地址
VUE_APP_GO_URL = '/bb' //请求地址
VUE_APP_ENV_DESC = '开发环境'
2. 根目录下新建文件.env.prod
NODE_ENV = 'production'
VUE_APP_PHP_URL = '正式环境ip地址,http://xxxx' //请求地址
VUE_APP_GO_URL = '正式环境ip地址,http://xxxx' //请求地址
VUE_APP_ENV_DESC = '正式环境'
3. 根目录下新建文件vue.config.js
module.exports = {
// 基本路径
publicPath: process.env.NODE_ENV === 'production' ? './' : '/' ,
// 输出文件目录
outputDir: 'dist',
// 静态资源存放的文件夹(相对于ouputDir)
assetsDir: "./static",
indexPath:"./index.html",
// eslint-loader 是否在保存的时候检查
lintOnSave: false,
runtimeCompiler: false,
// 生产环境是否生成 sourceMap 文件
productionSourceMap: false,
devServer: {
// open: process.platform === 'darwin',
open: true, //将服务启动后默认打开浏览器
host: 'localhost',
port: 8080,
https: false,
hotOnly: false,
proxy: { // 设置代理
'/aa':{
target:'http://localhost:1234/'
},
'/bb':{
target:'http://localhost:1111/'
}
}
}
}
4. package.json文件中配置打包命令
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build --mode prod",
"test": "vue-cli-service build --mode dev",
"lint": "vue-cli-service lint"
},
二、Axios封装
1.封装请求
代码如下(示例):
import axios from 'axios'
import qs from 'qs'
const phpUrl = process.env.VUE_APP_PHP_URL;
const goUrl = process.env.VUE_APP_GO_URL;
// 生成一个 axios 实例
const instance = axios.create({
baseURL: new RegExp("^aa").test(options.url) ? phpUrl : goUrl, // api 的 base_url
timeout: 5000 // 请求 超时配置
})
// 请求 拦截器
instance.interceptors.request.use(config => {
config.withCredentials = true
if (config.headers['Content-Type'] === 'application/json') {
config.data = JSON.stringify(config.data)
}
if (config.headers['Content-Type'] === 'multipart/form-data') {
return config
}
if (config.method === 'post' || config.method === 'put' || config.method === 'delete') {
if (typeof (config.data) !== 'string') {
config.data = qs.stringify(config.data)
}
}
return config
}, error => {
Promise.reject(error)
})
// 响应 拦截器
axios.interceptors.response.use(response => {
// 对响应数据做处理
return response
}, error => {
// 对响应错误做处理
return Promise.reject(error)
})
export default instance
2.引入使用
代码如下(示例):
import instance from './Axios'
//GET
export function getList(params){
return instance({
url:'/对应路径',
method:'get',
params
})
}
//POST
export function postData(data){
return instance({
url:'/xxx',
method:'post',
headers:{'Content-Type':'application/json'},
data
})
}