I am trying to configure a React + Vite application such that the frontend is able to talk to a backend webserver which is running on the same host at port 5555.
I have tried to configure Vite to use a reverse proxy such that requests for routes at /api
are redirected to the correct port number for the backend.
This is my vite.config.js
:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
server: {
proxy: {
'/api': {
target: 'http://localhost:5555',
changeOrigin: true,
secure: false,
}
}
}
})
When I run npm run dev
, and load my application frontend using a web browser, I obtain the following error in the console log.
This error is triggered by some code in the React app which makes an axios post request to the backend at /api/example_endpoint
. axios.post('/api/example_endpoint', {});
14:16:57 [vite] http proxy error: /api/example_endpoint
Error: connect ECONNREFUSED ::1:5555
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1549:16) (x2)
From the log message it looks to me as if the request is being made to an ipv6 address rather than an ipv4. Does that check out? If so what should I do to fix it?
localhost
does not seem to work. I tried replacing localhost
with 127.0.0.1
and now it does work.
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
server: {
proxy: {
'/api': {
target: 'http://127.0.0.1:5555',
changeOrigin: true,
secure: false,
}
}
}
})