在根目录下的vite.config.js文件
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
server: {
proxy: {
'/api': {
target: 'https://bj.ke.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
},
'/abdr': {
target: 'https://miao.baidu.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/abdr/, '')
},
}
},
plugins: [vue()]
})
以下为几种跨域配置方法,任选使用即可
export default {
server: {
proxy: {
// 字符串简写写法
'/foo': 'http://localhost:4567/foo',
// 选项写法
'/api': {
target: 'http://jsonplaceholder.typicode.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '')
},
// 正则表达式写法
'^/fallback/.*': {
target: 'http://jsonplaceholder.typicode.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/fallback/, '')
}
}
}
}
官网链接
https://vitejs.cn/config/#server-open