vue本地測試和打包上線,接口不同域名,測試需要跨域和正式不需要跨域的解決方法
通過判斷本地環境還是打包環境
定義全局變量,在global.vue中定義:
<script type="text/ecmascript-6">
const BASE_URL = ''
export default{
BASE_URL
}
</script>
在main.js 中引入:如
import global_ from '@/components/global.vue'
掛載到vue 實例中:
Vue.prototype.GLOBAL = global_
//打包環境判斷
if(process.env.NODE_ENV == 'production'){
Vue.prototype.GLOBAL.BASE_URL=" 部署服務調用正式地址"
}else{
//不用跨域
Vue.prototype.GLOBAL.BASE_URL="開發測試地址"
//跨域,proxyTable代理,自定義如/api
Vue.prototype.GLOBAL.BASE_URL="/api"
}
在config index.js 配置如下:
proxyTable: {
'/api': {
target: 'http://xxxxx.cn',//設置你調用的接口域名和端口號 別忘了加http
changeOrigin: true,
pathRewrite: {
'^/api': '/' // 這里理解成用‘/api’代替target里面的地址,后面組件中我們掉接口時直接用api代替 比如我要調用'http://40.00.100.100:3002/user/add',直接寫‘/api/user/add’即可
}
}
},
接下來你的接口地址可以這樣寫啦:
axios.post(this.GLOBAL.BASE_URL+'/huananhospital/findGoodByTypeId').then((res)=>{
})
