Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vite react proxy sends requests to different endpoints depending on current location

After switch to vite, I am trying to mimic proxy: "http://localhost:5000" which I previously used in package.json

Here is my vite config

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      "/api": {
        target: "http://localhost:5000",
        changeOrigin: true,
        secure: false,
      },
    },
  },
});

I have react app running on port 3000. When I send a request in the root url (http://localhost:3000) everything works fine

const { data } = await axios.get("api/user/me");

  • Well, not really fine. Even though proper data is returned in response, in the console request gets sent to http://localhost:3000/api/user/me instead of http://localhost:5000/api/user/me. Can anyone explain this behaviour?

The main problem is that when I navigate to another page (e.g. http://localhost:3000/dashboard), then the same request gets sent to http://localhost:3000/dashboard/api/user/me.

What am I doing wrong? I want to send requests to http://localhost:5000, no matter the location

I found a workaround by specifying FE url before every request const { data } = await axios.get("http://localhost:3000/api/user/me");, but still is there a way to mimic package.json proxy behaviour?

like image 631
pakut2 Avatar asked May 30 '26 17:05

pakut2


1 Answers

I resolved the issue by changing axios defaults

axios.defaults.baseURL = `http://localhost:5000`

By doing this I achieved what I was going for. Requests get sent to the proper endpoint no matter the location

like image 103
pakut2 Avatar answered Jun 01 '26 06:06

pakut2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!