3

I want to change base URL of HTTP requests from host address of Vite.js app (http://localhost:5173) to host address of my ASP .NET API (http://localhost:5815) on dev mode (npm run dev).

enter image description here

But I have such error during run of my Vite-Vue app after apply proxy to redirecting requests:

enter image description here

My vite.config.js file:

import { fileURLToPath, URL } from 'node:url'

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
  ],
  build: {
    cssCodeSplit: false,
  },
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  server: {
    proxy: {
      '/': {
        target: 'http://localhost:5815',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\//, '')
      }
    }
  }
})

I also tried such vite.config.js

import { fileURLToPath, URL } from 'node:url'

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
  ],
  build: {
    cssCodeSplit: false,
  },
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:5815',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  }
})

Result was that:

enter image description here

What I should do in order to redirect all of my HTTP requests from localhost:5173 to localhost:5815 during run my in dev mode (npm run dev)?

I mention only that similar project with only Vue.js, worked with this vue.config.js:

const { defineConfig } = require('@vue/cli-service');

module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,
  devServer: {
    proxy: 'http://localhost:5815',
  },
});

1 Answer 1

2

In any case, you need a path different from the root (since from the root, the website's assets such as CSS, JS, and other files are loaded).

export default defineConfig({
  server: {
    proxy: {
      // With options:
      // http://localhost:5173/api/users
      //   -> http://localhost:5815/users
      '/api': {
        target: 'http://localhost:5815',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''), // It removes the /api from the request address, so it will truly be used only for differentiation
      },
    },
  },
})

Every address associated with /api will be redirected to localhost:5815. In the example, you see accessing localhost:5815/some-endpoint:

If the request is not made with the prefix set in the proxy, it will not work. You must assign a prefix from the server.host to every proxy.

// Before (NOT WORKING)
// The proxy cannot be recognized without a prefix.
axios.get('/some-endpoint') // With what you are currently trying, it will never work from the root
// Call http://localhost:5173/some-endpoint (Vite Host)

IMPORTANT: You must use the server.host + /api prefix so that the proxy can redirect the request during operation.

// After (SUCCESSFULLY)
axios.get('/api/some-endpoint') // With the /api proxy route defined now, it works
// Call http://localhost:5815/some-endpoint (Your Custom API)

How can this target proxy address be modified in the live production version? Simply check whether Vite is currently running in dev or prod mode. Accordingly, the address can be dynamically set.

const API_URI = process.env.NODE_ENV === 'production'
  ? 'http://example.com'    // in prod
  : 'http://localhost:5815' // in dev

export default defineConfig({
  server: {
    // (DEV MODE) With options:
    // http://localhost:5173/api/users
    //   -> http://localhost:5815/users
    //
    // (PROD MODE) With options:
    // http://yourdomain.com/api/users
    //   -> http://example.com/users
    proxy: {
      '/api': {
        target: API_URI,
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
    },
  },
})
Sign up to request clarification or add additional context in comments.

9 Comments

I feel that you want to achieve the impossible. You want to say that the requests coming out of your application sometimes need to be loaded from localhost:5173, such as the app's index.html, JS files, CSS files, images, fonts, etc., but you also want to fetch your API routes from here in a mixed manner. If rewriting the routes is not feasible, you are in a difficult situation. Because you have to declare each API route individually, such as /getusers, /getposts, /getarticles, etc., and redirect each one to its counterpart on localhost:5815.
I find it more practical to create a common /api route under which you will handle these. The /api is just a common group name in your frontend app, as mentioned, it won't be included in the URL thanks to path.replace(). So, following my solution, it's your job to add a /api prefix before each API route call in your frontend application.
So when you call the /api/getarticles example endpoint, Vite will automatically invoke http://localhost:5815/getarticles, thanks to the /api proxy. Due to path.replace(), as you can see, the /api prefix will not be included in the new URL address.
You don't need to include the domain in the URL address; Vite will handle that for you since you've set up the proxy. In this case, localhost:5173/api/getarticles will be redirected to localhost:5815/getarticles. If this is not suitable for you, then you would have to individually set up a proxy for each address. However, I believe this is not a good solution and is not standard practice. In any case, I recommend consolidating your API routes under the mentioned API (or a name of your choice) group, so you can easily identify that URLs starting with this group name are API queries.
you explained me this perfectly - I modified according to your advices and it work!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.