项目开发
.env(在所有的环境中被载入)
# 环境
NODE_ENV = "development"
.env.staging(只在测试环境中被载入)
# staging 预演环境,即线上的dev环境
NODE_ENV = "production"
# publicPath
VUE_APP_PUBLIC_PATH = '/'
.env.production(只在生产环境中被载入)
# 环境
NODE_ENV = "production"
# publicPath
# VUE_APP_PUBLIC_PATH = 'https://cdn.jiaoyihu.com/'
# VUE_APP_PUBLIC_PATH = '/'
VUE_APP_PUBLIC_PATH = 'http://h5.promotion.jiaoyihu.com'
public-path.js
const publicPath = process.env.VUE_APP_PUBLIC_PATH
module.exports = publicPath
subdirectory-path.js
const time = new Date().getTime()
const serveName = 'promotion-h5'
const subdir = serveName + '/' + time
module.exports = subdir
vue.config.js
module.exports = {
// 为项目中的所有资源指定一个基础路径,它被称为公共路径(publicPath)
publicPath: isProduction ? publicpath : '/',
// 构建文件的目录
outputDir: 'dist',
// 生成静态资源的目录
assetsDir: subdirectoryPath
}
线上静态资源路径:http://h5.promotion.jiaoyihu.com/promotion-h5/1610172249953/img/ic_home_daishou@2x.6ce160ad.png
本地静态资源路径:/promotion-h5/1610077464291/img/ic_home_daishou@2x.6ce160ad.png
创建 axios 实例
可以使用自定义配置新建一个 axios 实例
axios.create([config])
const instance = axios.create({
// 设置超时时间30秒
timeout: 30000,
// 请求的baseUrl
baseURL: baseUrl,
// 请求头部信息
headers: {
'Content-Type': 'application/json'
},
// 修改请求数据
transformRequest: [
function (data, headers) {
return JSON.stringify(data)
}
],
// 跨域请求时允许携带凭证(cookie)
withCredentials: process.env.NODE_ENV === 'production'
})
全局的 axios 默认值
axios.defaults.baseURL = 'https://api.example.com'
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
data和contentType配合使用:
contentType: "application/x-www-form-urlencoded"
// 对应的data类型
data: "name='张三'&age=20"
contentType: "application/json"
// 对应的data类型
data: JSON.stringify({
name: "张三",age: 20})即data: {
"name": "张三","age": 20}
例子:
data: {
name: '张三',
age: 18
}
// 修改请求数据
transformRequest: [function (data, headers) {
let ret = ''
for (let it in