Vite开发时如何代理后端API请求?

FSD-海利 阅读 45

我用 Vite 搭了个前端项目,后端是本地跑的 Node 服务,端口 3001。现在前端发请求总是跨域,试过在 vite.config.js 里配 proxy,但好像没生效。

比如我 fetch /api/users,想让它转发到 http://localhost:3001/api/users,但浏览器还是直接请求了前端端口(5173),导致 CORS 错误。我是不是哪里配错了?

这是我的配置:

export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:3001',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^/api/, '')
      }
    }
  }
})
我来解答 赞 4 收藏
二维码
手机扫码查看
1 条解答
UI常青
UI常青 Lv1
你这个配置基本没问题,但有个小坑:Vite 的 proxy 是基于 http-proxy-middleware 的,rewrite 的写法不对。你写的 path.replace(/^/api/, '') 里那个正则没转义斜杠,而且 Vite 官方推荐用 rewrite 的话应该用函数返回新路径,不过更简单的办法是直接用 pathRewrite 属性。

另外你得确认下:Vite 开发服务器是不是真的重启了?改完配置没重启的话是不生效的。

先给你一个能用的写法:

export default defineConfig({
server: {
proxy: {
'/api': {
target: 'http://localhost:3001',
changeOrigin: true,
secure: false,
rewrite: path => path.replace(/^/api/, '')
}
}
}
})


注意几个关键点:正则里的斜杠要转义成 /^/api/,或者干脆用字符串匹配也行;secure: false 是为了跳过 HTTPS 校验(虽然本地一般用不到,但加了更稳妥);changeOrigin: true 这个是对的,保证请求头里的 Origin 会变成 target 的地址。

另外你前端调用的时候记得路径要写成 /api/users,别写成 api/users(少个斜杠也会不匹配)。

如果还是不行,可以加个日志看看请求有没有进到 proxy 里:

export default defineConfig({
server: {
proxy: {
'/api': {
target: 'http://localhost:3001',
changeOrigin: true,
secure: false,
configure: (proxy, options) => {
proxy.on('proxyReq', (proxyReq, req, res) => {
console.log('代理中...', req.url, '→', options.target + req.url)
})
},
rewrite: path => path.replace(/^/api/, '')
}
}
}
})


跑起来后看控制台有没有打印,能打印说明代理配置生效了,问题就出在别处(比如后端没开 CORS 或者端口没监听)。

对了,Vite 的 devServer 配置里 proxy 是区分大小写的,你路径别写成 /API 或者其他大小写混搭,这个踩过坑,debug 了半小时才发现是大小写问题……
点赞
2026-02-24 11:06