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

9.1k Views Asked by At

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?

3

There are 3 best solutions below

2
pakut2 On

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

1
Floratoby On

I solved this problem by using Axios.

  1. Create a new file. I called mine emailApi.

  2. Setup your axios, like so:

    export const emailApi = axios.create({baseURL: "http://localhost:<yourPortNumber>"})
    
  3. Done! Whenever you want to send a request to your server, import the emailApi and you're good.

Also in your server, make sure to install cors and set it as a middleware, like so:

express().use(cors({origin: <viteLocalServer>}))
0
easyScript On

I have same issue and I menage to solve with absolute path in axios call like this: axios('/api/user/me'). Before that I configure Vite in vite.config.js like this:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

//https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:5001/',
        changeOrigin: true,
      },
    },
  },
})

For some reason my server can't start at port 5000 that's why I set port to 5001.