一个vue项目中配置请求多个服务端解决方案

前言:最近项目开发中,遇到这么个情况,一个前端项目需要搭配两个服务端接口,所以前端的代理需要重新修改,遂记录

一、解决方案

1.1 描述接口context-path

后端的两个接口服务请求前缀,如下:

前缀1: /mini-rest
前缀2: /
1.2 vue.config.js配置
devServer: {
  port: 8005,
  proxy: {
    // 第一台服务器配置 
    '/mini-rest': {
      target: 'http://localhost:8085',
      ws: true,
      changeOrigin: true,
      pathRewrite: {
        '^/mini-rest': '/mini-rest'
      }
    },
    // 第二台服务器配置 
    '/': {
      target: 'http://localhost:8899',
      ws: true,
      changeOrigin: true,
      pathRewrite: {
        '^/': '/'
      }
    } 
  }
}
1.3 axios修改
// api base_url,设置前缀不存在
const BASE_URL = ''
// 创建 axios 实例
const service = axios.create({
 baseURL: BASE_URL, 
 timeout: 6000 // 请求超时时间
})

此时axios不需要直接指定baseUrl配置

1.4 发送请求
// 请求前缀为“/”
dibootApi.get("/trans").then(res => {
 console.log('/', res)
}).catch(err => {
 console.log(err)
})
// 请求前缀为“mini-rest”
dibootApi.get("/mini-rest/getTest").then(res => {
 console.log('/mini-rest', res)
}).catch(err => {
 console.log(err)
})

注:请求的时候手动加上前缀

1.5 结果展示

结果

总结

  • 多个接口服务的情况下,如果前缀是"/",要将其放在proxy配置的最后一部分,代理的时候是从上往下查找的,如果放在最上面其他服务也会被该配置代理掉

你可能感兴趣的:(vue,解决方案,vue)