SoFunction
Updated on 2025-04-05

Vite/Vuecli configure proxy to solve cross-domain problems

vite/Vuecli configure proxy to solve cross-domain

On the code

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';
// /config/
export default defineConfig({
  server: {
    port: 9090,
    strictPort: true, // Strict port true: If the port has been used, it will be directly exited and no subsequent port attempts will be made.    /**
      * @description Solution to chrome settings origin: * is also cross-domain mechanism, proxy/api prefix to service base address
      * The final address will splice the baseUrl:/dev proxy set by axios into [target][/dev][/xxx/yyy]
      */
    proxy: {
      '/dev': {
        target: '', // Interface base address        rewrite: path => {
          (path); // Print [/dev/xxx/yyy] This is the url that http-proxy needs to request. If the server's real address does not have a /dev prefix, you must replace it. If there is one, you can not replace it.          return (/^\/dev/, '');
        }
      }
    }
  },
  plugins: [vue()],
  resolve: {
    alias: {
      '@': resolve(__dirname, '.', 'src') // Set @ to point to src    }
  },
})

Vuecli configuration

devServer: {
    port: '9090',
    proxy: {
      [.VUE_APP_PREFIX]: {
        target: .VUE_APP_BASEURL,
        secure: true,
        changeOrigin: true,
        pathRewrite: {
          [`^${.VUE_APP_PREFIX}`]: '',
        },
      },
    },

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.