vue/cli 3 配置多個代理服務器

  1. 在與src同級目錄新建vue.config.js
  2. vue.config.js
    module.exports = {
        publicPath: '/',
      
        outputDir: 'dist',
      
        assetsDir: 'static',
      
        filenameHashing: true,
      
        devServer: {
          open: true,  // 自動打開瀏覽器
      
          host: '127.0.0.1',
      
          port: 8081,
      
          https: false,
      
          hotOnly: false,
    
          disableHostCheck: true,
      
          proxy: {
              "/api": {
                  target: 'http://xxxxxxx', // 這個地址結尾我原本加了一個‘/’,然後一直報404,去掉就好了
                  changeOrigin: true,
                  pathRewrite: {
                      '^/api': '/'
                  }
              },
              '/bpi': {
                  target: "http://xxxxxx",
                  changeOrigin: true,
                  pathRewrite: {
                    '^/bpi': '/'
                }
              },
              '/cpi': {
                  target: 'http://',
                  changeOrigin: true,
                  pathRewrite: {
                    '^/cpi': '/'
                }
              }
          },
      
          before: app => {
          }
        },
        // 構建時開啓多進程處理 babel 編譯
        parallel: require('os').cpus().length > 1,
      
        // https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-plugin-pwa
        pwa: {},
      
        // 第三方插件配置
        pluginOptions: {}
      };

    因爲數據在不同的服務器,所以配置proxy 方便拿取數據

  3. 在main.js裏面,設置baseURL

axios.defaults.baseURL = '';

Vue.prototype.$http=axios;  這裏根據實際需要設置請求頭之類的

使用時

this.$http({
    method: 'post',
    url: '/api/xxx/xxx',
    data: params
}).then(res => {
    console.log(res.data)
}).catch(error => {
    console.log(error)
})

4.重啓項目,一定要重啓項目!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章