Vite代理配置不生效问题

1、问题:

在写Vite+vue3.0项目时,配置vite代理,遇到不起效的问题,具体如下:

// vite.config.ts
proxy: {
      '/api':  ' http://localhost:3000'
    }

如上简写的写法,代理不生效

2、解决方案:

查看官网后,改用如下写法生效

 //vite.config.ts

proxy: {
    '/api': {
      target: 'http://localhost:3000',
      changeOrigin: true,
      rewrite: (path) => path.replace(/^\/api/, '')
    }
  }

3、原因排除:

经过测试发现,不添加“rewrite”属性时,代理配置仍存在不生效的情况,

例如:

// 此写法可能存在代理不生效的情况
proxy: {
    '/api': {
      target: 'http://localhost:3000',
      changeOrigin: true
    }
  }

 4、其他

在vite5.0版本中略有不同,请参考如下:

const BaseURL = "/api";
 // vite.config.js
 server: {
    //用来配置跨域
    host: '0.0.0.0',
    port: 80,
    proxy: {
      '/api': {
        target: 'http://localhost:8080',//目标服务器地址
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      },
    }
  }

 

posted @ 2023-03-30 11:37  莫颀  阅读(7328)  评论(0编辑  收藏  举报