Search code examples
javascriptvue.jsvuejs3vite

Redirecting of HTTP request on Vite-Vue app - DEV mode


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',
  },
});

Solution

  • 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/, ''),
          },
        },
      },
    })