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

1,976 阅读1分钟
  • 花有重开日,人无再少年

一、解决方案

1.1 描述接口context-path

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

前缀1: /bryant
前缀2: /

1.2 vue.config.js配置

devServer: {
  port: 8005,
  proxy: {
    // 第一台服务器配置 
    '/bryant': {
      target: 'http://localhost:8081,
      ws: true,
      changeOrigin: true,
      pathRewrite: {
        '^/bryant': '/bryant'
      }
    },
    // 第二台服务器配置 
    '/': {
      target: 'http://localhost:8082',
      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 发送请求

// 请求前缀为“/”
this.$http.get("/basketball").then(res => {
 console.log('/', res)
}).catch(err => {
 console.log(err)
})
// 请求前缀为“bryant”
this.$http.get("/bryant/mvp").then(res => {
 console.log('/bryant', res)
}).catch(err => {
 console.log(err)
})
 

总结

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