vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vue项目多代理配置

Vue项目配置多个代理服务器的多种方案

作者:江城开朗的豌豆

今天咱们来聊聊Vue项目中一个非常实用的技巧 - 如何配置多个代理服务器,相信不少小伙伴在对接多个后端服务时都遇到过跨域问题,这篇文章就教你如何优雅解决,需要的朋友可以参考下

为什么需要多代理?

在实际开发中,我们经常会遇到这些情况:

这时候,单一代理配置就捉襟见肘了。下面我就分享几种实用的多代理配置方案。

方案一:vue.config.js基础配置

这是最基础的代理配置方式,适合大多数场景。

// vue.config.js
module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'http://我的测试环境.com',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      },
      '/other-api': {
        target: 'http://我的其他服务.com',
        changeOrigin: true,
        pathRewrite: {
          '^/other-api': ''
        }
      }
    }
  }
}

使用时代码中这样调用:

// 调用测试环境API
axios.get('/api/user/info')

// 调用其他服务API
axios.get('/other-api/product/list')

优点

方案二:环境变量动态切换

如果需要根据环境动态切换代理目标,可以这样配置:

// vue.config.js
module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: process.env.VUE_APP_API_BASE,
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
}

然后在不同环境的.env文件中配置:

# .env.development
VUE_APP_API_BASE=http://我的开发环境.com

# .env.production
VUE_APP_API_BASE=http://我的生产环境.com

方案三:更灵活的多代理配置

对于复杂场景,可以这样组织代码:

// vue.config.js
const proxyTable = {
  dev: {
    '/api': {
      target: 'http://dev.我的服务.com',
      // 其他配置...
    },
    '/auth': {
      target: 'http://dev.我的认证服务.com',
      // 其他配置...
    }
  },
  test: {
    '/api': {
      target: 'http://test.我的服务.com',
      // 其他配置...
    }
    // 其他代理...
  }
}

module.exports = {
  devServer: {
    proxy: proxyTable[process.env.NODE_ENV] || proxyTable.dev
  }
}

实战案例:电商项目多服务代理

假设我们开发一个电商项目,需要对接:

  1. 用户服务 user-service
  2. 商品服务 product-service
  3. 订单服务 order-service

配置如下:

module.exports = {
  devServer: {
    proxy: {
      '/user': {
        target: 'http://user-service.我的公司.com',
        changeOrigin: true,
        pathRewrite: {'^/user': ''}
      },
      '/product': {
        target: 'http://product-service.我的公司.com',
        changeOrigin: true,
        pathRewrite: {'^/product': ''}
      },
      '/order': {
        target: 'http://order-service.我的公司.com',
        changeOrigin: true,
        ws: true,  // 如果需要WebSocket
        pathRewrite: {'^/order': ''}
      }
    }
  }
}

使用时:

// 获取用户信息
axios.get('/user/info')

// 获取商品列表
axios.get('/product/list')

// 提交订单
axios.post('/order/create', orderData)

常见问题解决方案

1. 代理不生效怎么办?

2. WebSocket代理失败?

proxy: {
  '/socket': {
    target: 'ws://我的websocket服务.com',
    ws: true,
    changeOrigin: true
  }
}

3. 需要携带Cookie怎么办?

proxy: {
  '/api': {
    target: 'http://我的服务.com',
    changeOrigin: true,
    cookieDomainRewrite: {
      "*": "localhost" // 把cookie域名重写为本地
    }
  }
}

配置建议

根据我6年的项目经验,建议:

  1. 代理路径前缀要语义化(如/api、/user等)
  2. 复杂项目建议按功能模块划分代理
  3. 生产环境记得移除或替换代理配置
  4. 使用环境变量管理不同环境的代理目标
  5. 定期检查代理配置,避免冗余

总结

通过合理配置多个代理,我们可以:

写在最后​

以上就是Vue项目配置多个代理服务器的操作指南的详细内容,更多关于Vue项目多代理配置的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文