1、方便多端打包,baseURL引用全局变量
◇ static下新建config.js文件,设置一个BASE_API
var BASE_API='/default'
复制代码
◇ 根目录下找到.eslintrc.js文件 修改配置
修改完毕则可以全局使用这个变量(防止编辑器报错提醒)
◇ 在index.html引入这个静态js文件,为方便打包可以再写一个打包后的路径
2、封装的axios文件修改
脚手架搭建的一般为baseURL: process.env.BASE_API
// 创建axios实例
var service = axios.create({
baseURL: process.env.BASE_API, // api的base_url
timeout: 1200000, // 请求超时时间
transformRequest: [
function (data) {
// Do whatever you want to transform the data
let ret = ''
for (const it in data) {
ret +=
encodeURIComponent(it) +
'=' +
encodeURIComponent(data[it]) +
'&'
}
return ret
}
],
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
}
})
复制代码
开始将baseURL直接修改为baseURL: BASE_API
但发现页面修改这个值 请求依旧不变
正确的修改是在use时修改 于是将baseURL先设置空字符串 baseURL: ''
在return config前再对url重新设置下
// request拦截器
service.interceptors.request.use(config => {
if (window.localStorage.getItem('tooken')) {
config.headers['x-auth-token'] = window.localStorage.getItem('tooken') // 让每个请求携带自定义token 请根据实际情况自行修改
}
config.url = BASE_API + config.url
return config
}, error => {
// Do something with request error
// router.push({
// path: '/login'
// })
console.log(error, '请求错误') // for debug
Promise.reject(error)
})
复制代码
文章