我正在尝试从 Flask 服务器(localhost:5000)使用我的 Vite 应用程序(localhost:5173)获取数据。我所有的 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);
});
}
},
}
}
})
这些是在vite.config中错误处理的客户端控制台输出:
Sending Request to the Target: GET /api/home/
Received Response from the Target: 200 /api/home/
这是我的获取函数:
fetch('/api/home')
.then((res) => console.log(res))
// .then((res) => res.json())
// .then((data: object[]) => {
// setPostData(data)
// })
这是上述console.log的输出(不明白为什么fetch仍然命中localhost:5173端点):
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都不太熟悉,但是有使用Express和Node、有使用React/Vite的经验。
我试过:
- 按照Vite文档进行操作
- 在vite.config中将server.proxy路径更改为'/' - 这仅会提供我的Flask应用程序,没有Vite
- 在vite.config中添加
secure: false
- 一位类似问题上我找到的解决方案 - 这并没有起作用 - 在vite.config中添加
ws: true
- 在此处找到的另一个解决方案 - 没有起作用 - 将server.proxy url从'/api'更改为'/' - 这提供了我的Flask应用程序,并且无法查看我的Vite前端
- 在我的fetch中添加Access-Control-Allow-Origin头 - 这没有任何作用
- 添加server.proxy.configure选项以尝试查找错误 - 这会混淆性地响应200 - 我预期会出现400