问题描述:
Access to XMLHttpRequest at ‘http://lxxx:9407/login‘ from origin ‘http://localhost:8888‘ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

error
只需要配置vite.config.ts中的server-proxy选项。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
server: {
proxy: {
"/api": {
target: "http://xxl:9407",
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ""),
},
},
}
})

使用:

1
2
3
4
5
const httpClinet = axios.create({
baseURL: '/api',
timeout: 5000,
headers: { 'Content-type': 'application/x-www-form-urlencoded'}
})

baseURL处使用/api来代替原来的链接路径就好了。