4

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?

pakut2
  • 500
  • 5
  • 21
  • 1
    For your main problem of running the code on a dashboard url or somewhere else, just use an absolute path: `axios.get("/api/user/me")`. – Bergi May 18 '22 at 23:32
  • "*in the console request gets sent to `http://localhost:3000/api/user/me`*" - that sounds normal: that's the current origin. I don't know vite, but if that is a **server** configuration, I'd expect the *server* that runs at `localhost:3000` to proxy the request - the client doesn't care. – Bergi May 18 '22 at 23:35

2 Answers2

2

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

pakut2
  • 500
  • 5
  • 21
-1

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>}))
tdy
  • 36,675
  • 19
  • 86
  • 83
Floratoby
  • 34
  • 2
  • How is this different to the answer OP already posted almost a year ago? Also, if you're using a reverse-proxy, you don't need CORS – Phil Jan 31 '23 at 04:18