Vue项目代理+baseURL的设置
Vue.config.js里
module.exports = {
devServer: {
host: 'localhost',//target host
port: 8080,
//proxy:{'/api':{}},代理器中设置/api,项目中请求路径为/api的替换为target
proxy: {
'/api': {
target: 'http://10.191.4.131:18088/',//代理地址,这里设置的地址会代替axios中设置的baseURL
changeOrigin: true,// 如果接口跨域,需要进行这个参数配置
//ws: true, // proxy websockets
//pathRewrite方法重写url
pathRewrite: {
'^/api': '/'
//pathRewrite: {'^/api': '/'} 重写之后url为http://10.191.4.131:18088/xxxx
//pathRewrite: {'^/api': '/api'} 重写之后url为 http://10.191.4.131:18088/api/xxxx
}
},
'jx': {}
}
},
}
设置baseURL
在Vue根目录下创建不同环境下的变量配置文件
.env.development
# just a flag
ENV = 'development'
# base api
VUE_APP_BASE_API = '/'
#开发用
.env.production
# just a flag
ENV = 'production'
# base api
VUE_APP_BASE_API = '/prod-api'
#生产用
request.js
let baseURL = ''
if (process.env.NODE_ENV === 'development') {
baseURL = process.env.VUE_APP_BASE_API + 'jx/platform/api/v1.0/'
} else {
baseURL = 'http://10.191.4.131:18088/jx/platform/api/v1.0/'
}
本文介绍了在Vue项目中如何设置devServer代理和baseURL,以实现跨域请求。通过在Vue.config.js中配置proxy,将'/api'路径指向指定服务器地址,并使用pathRewrite重写URL。同时,根据不同的环境(development和production),在.env文件中设置VUE_APP_BASE_API,request.js中根据环境动态获取baseURL,确保请求路径正确。
731

被折叠的 条评论
为什么被折叠?



