vite 配置单个,多个代理
文章类型:Vue
发布者:hp
发布时间:2025-02-19
在vite配置中,我们需要进行服务器代理,主要目的是解决跨域问题,保持域名、端口或访问协议一致,
1:单个方式
const instance = axios.create({
baseURL: '/api',
timeout: 120000
})
server: {
host: '0.0.0.0',
proxy: {
'/api': {
target: 'https://www.cqhxb.com',
changeOrigin: true, // 允许跨域
ws: true, // 允许websocket代理
// 重写路径 --> 作用与vue配置pathRewrite作用相同
rewrite: path => path.replace('\/api'), '')
}
}
}
实际请求地址为
https://www.cqhxb.com/api/xxx
2:多个配置
server: {
https: false,
proxy: {
"/api/front": {
target: "https://www.cqhxb.com",
changeOrigin: true, // 允许跨域
rewrite: (path) => path.replace(/^\/api\/front/, ""),
},
"/api/admin": {
// 配置需要代理的路径 --> 这里的意思是代理http://localhost:80/api/后的所有路由
target: "https://www.cqhxb.com",
changeOrigin: true, // 允许跨域
ws: true, // 允许websocket代理
// 重写路径 --> 作用与vue配置pathRewrite作用相同
rewrite: (path) => path.replace(/^\/api\/admin/, ""),
},
},
},
实际请求地址为
https://www.cqhxb.com/api/front/xxx
https://www.cqhxb.com/api/admin/xxx
1:主要是避免跨域,保持域名、端口或者访问协议一致
2:避免重复性写域名,增加可维护性