vite.config.js如何配置多个跨域

x33g5p2x  于2021-10-21 转载在 其他  
字(0.7k)|赞(0)|评价(0)|浏览(502)

vue3.0根目录下vue.config.js文件

  1. export default defineConfig({
  2. server: {
  3. proxy: {
  4. // 字符串简写写法
  5. '/foo': 'http://localhost:4567',
  6. // 选项写法
  7. '/api': {
  8. target: 'http://',
  9. changeOrigin: true,
  10. rewrite: (path) => path.replace(/^\/api/, '')
  11. },
  12. // 正则表达式写法
  13. '^/fallback/.*': {
  14. target: 'http://',
  15. changeOrigin: true,
  16. rewrite: (path) => path.replace(/^\/fallback/, '')
  17. },
  18. // 使用 proxy 实例
  19. '/api': {
  20. target: 'http://',
  21. changeOrigin: true,
  22. configure: (proxy, options) => {
  23. // proxy 是 'http-proxy' 的实例
  24. }
  25. }
  26. }
  27. }
  28. })

需要注意的是:我刚开始这样配置

  1. server: {
  2. proxy: {
  3. "/api": {
  4. target: 'http://39.',
  5. changeOrigin: true,
  6. rewrite: path => path.replace(/^\/api/, '')
  7. },
  8. "/api2": {
  9. target: 'http://10.',
  10. changeOrigin: true,
  11. rewrite: path => path.replace(/^\/api2/, '')
  12. }
  13. },
  14. },

结果是配置跨域不成功,因为 rewrite是重置路径的后面的正则回匹配到api开头的所以第一个把第二个跨域覆盖了,所以改成两个不一样开头的名字就可以了

相关文章