配置Vite代理转发Flask后端失败:请求仍指向Vite端口排查
Vite代理配置后fetch请求仍指向本地端口的问题
我正在运行部署于localhost:5173的Vite应用,需要请求部署于localhost:5000的Flask服务器数据。所有API端点在Postman中均可正常调用,但按Vite官方文档配置代理后,fetch请求仍指向localhost:5173。
我的vite.config.ts配置
export default defineConfig({ plugins: [react()], server: { proxy: { "/api": { target: "http://127.0.0.1:5000", changeOrigin: true, secure: false, ws: true, configure: (proxy, _options) => { proxy.on('error', (err, _req, _res) => { console.log('proxy error', err); }); proxy.on('proxyReq', (proxyReq, req, _res) => { console.log('Sending Request to the Target:', req.method, req.url); }); proxy.on('proxyRes', (proxyRes, req, _res) => { console.log('Received Response from the Target:', proxyRes.statusCode, req.url); }); } }, } } })
代理日志输出
Sending Request to the Target: GET /api/home/ Received Response from the Target: 200 /api/home/
fetch请求代码
fetch('/api/home') .then((res) => console.log(res)) // .then((res) => res.json()) // .then((data: object[]) => { // setPostData(data) // })
控制台输出(显示请求指向本地端口)
type: 'basic', url: 'http://localhost:5173/api/home/', redirected: true, status: 200, ok: true, …
Postman返回的数据示例
[{ "comments": [], "created_at": "Thu, 23 Mar 2023 08:30:17 GMT", "likes": 2, "text": "Lorem ipsum", "title": "Morbi non quam nec dui luctus rutrum", "updated_at": "Thu, 23 Mar 2023 08:30:17 GMT", "user": "alesmonde0", "user_id": 1 }]
我刚接触Flask和TypeScript,但有React/Vite搭配Express和Node的开发经验,是不是有什么简单的细节被我忽略了?
已尝试的解决方法
- 严格遵循Vite官方文档配置代理
- 将
server.proxy路径改为'/'- 结果仅显示Flask应用,无法访问Vite前端页面 - 在vite.config中添加
secure: false- 无效果 - 在vite.config中添加
ws: true- 无效果 - 为fetch请求添加
Access-Control-Allow-Origin请求头 - 无作用 - 添加
server.proxy.configure选项排查错误 - 但返回200状态码,与预期的400不符
内容的提问来源于stack exchange,提问作者djbartolini
相关产品推荐
相关产品推荐

