Issue
I am trying to set a proxy in my frontend so that I can fetch() apis from my backend.
Here is my setup:
vite.config.ts:
server: {
proxy: { "/api": {
target: 'http://localhost:3001',
changeOrigin: true,
secure: false
}
}
},
frontend.tsx:
const Test: React.FC = () => {
useEffect(()=>{
fetch(`api/hello`)
.then(res => console.log(res))
}, [])
return(
<div>
hi
</div>
)
}
Backend:
@app.route('/api/hello', methods=['GET'])
def test():
return jsonify({"hi":"there"})
I get the error:
GET http://localhost:5173/api/hello net::ERR_ABORTED 500 (Internal Server Error)
It is using port 5173 for the fetch() and not 3001 which is what my server is listening on.
I have tried solutions such as: How to configure proxy in Vite? and it does not work.
I added some event listeners to the vite.config.ts file as follows:
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);
});
},
}
}
I got the following errors when I refreshed:
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)
```
Solution
I solved this by changing localhost to the localhost ip address
server: {
proxy: { "/api": {
target: 'http://127.0.0.1:3001',
changeOrigin: true,
secure: false
}
}
},
Why does this work and not localhost? We may never know...
Answered By - Null Salad
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.