Vue3, Vite, and TypeScript Cross-Domain Settings

I've recently been working on a project involving Vue3, Vite, and TypeScript. The frontend and backend are separate, and when the frontend requests the backend, the browser debug information reports a cross-origin error. I generally assume this is a backend configuration issue, but the backend code hasn't been adjusted. After some searching, I discovered that setting a proxy in vite.config.ts is the simplest solution.

I'm not a frontend developer, so I don't want to spend too much time researching the issue.

The vite.config.ts file is generated when Vite creates a Vue3 project. An example file is as follows:

 1import { fileURLToPath, URL } from 'node:url'
 2
 3import { defineConfig, loadEnv } from 'vite'
 4import vue from '@vitejs/plugin-vue'
 5import vueJsx from '@vitejs/plugin-vue-jsx'
 6
 7// https://vitejs.dev/config/
 8export default defineConfig((command, mode) => {
 9
10const env = loadEnv(mode, process.cwd(), '') // Load environment variables to prevent hardcoding
11
12console.log("env:", env) // Print environment variables for debugging purposes and checking which environment variables are in effect
13
14return {
15plugins: [vue(), vueJsx()],
16resolve: {
17alias: {
18'@': fileURLToPath(new URL('./src', import.meta.url))
19}
20},
21define: {
22__APP_ENV__: env.APP_ENV,
23},
24server: {
25port: env.VITE_PORT, // Front-end project running port
26https: false, // HTTPS, generally not required in development environments
27open: true, // Open a browser tab directly after running
28
29proxy: {
30'/api': {
31target: env.VITE_API_SERVER_URL, // Backend API interface address: http://127.0.0.1:8080
32ws: false, // Disable websockets
33changeOrigin: true,
34rewrite: (path) => path.replace(/^\/api/, 'api'), // Similar to nginx's rewrite, fill in what you need to retain after matching in the route
35},
36'/ws': {
37target: env.WS_API_SERVER_URL, // Backend API Websocket interface address: ws://127.0.0.1:8888
38ws: true, // Support websocket
39}
40}
41},
42}
43})

As shown above, after completing the configuration, in the Vue template script, use the axios library to perform a POST request. The target interface for the request is http://127.0.0.1:8080/api/xxx/

 1const results = await axios.post('/api/xxx/',
 2{
 3'foo1': 'bar1',
 4'foo2': 'bar2',
 5}
 6).then((res) => {
 7console.log('res:',res)
 8}).catch((error) => {
 9console.log('error:',error)
10})

If you have any questions about the above configuration, please refer to the official Vite official configuration documentation and carefully read the corresponding submodules.

Lastmod: Saturday, August 2, 2025

Translations: