我正在尝试在前端设置代理,以便可以从后端获取 fetch() api。
这是我的设置:
vite.config.ts:
server: {
proxy: { "/api": {
target: 'http://localhost:3001',
changeOrigin: true,
secure: false
}
}
},
前端.tsx:
const Test: React.FC = () => {
useEffect(()=>{
fetch(`api/hello`)
.then(res => console.log(res))
}, [])
return(
<div>
hi
</div>
)
}
后端:
@app.route('/api/hello', methods=['GET'])
def test():
return jsonify({"hi":"there"})
我收到错误:
GET http://localhost:5173/api/hello net::ERR_ABORTED 500(内部服务器错误)
它使用端口 5173 进行 fetch(),而不是我的服务器正在监听的端口 3001。
我尝试过以下解决方案: How to configure proxy in Vite? 但它不起作用。
我在 vite.config.ts 文件中添加了一些事件监听器,如下所示:
proxy: { "/api": {
target: 'http://localhost:3001',
changeOrigin: true,
secure: false,
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/hello
proxy error Error: connect ECONNREFUSED ::1:3001
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '::1',
port: 3001
}
3:45:38 p.m. [vite] http proxy error at /api/hello:
Error: connect ECONNREFUSED ::1:3001
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1494:16) (x3)
```
最佳答案
我通过将 localhost 更改为 localhost IP 地址解决了这个问题
server: {
proxy: { "/api": {
target: 'http://127.0.0.1:3001',
changeOrigin: true,
secure: false
}
}
},
为什么这个有效,而不是本地主机?我们可能永远不会知道...
关于reactjs - Vite + React + Flask 不代理前端到后端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77218109/