一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

vue配置请求多个服务端解决方法代码

时间:2021-03-30 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下vue配置请求多个服务端解决方法代码,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

一、解决方案

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)
})

热门栏目