配置 Vite 的代理服务器。需要修改 vite.config.ts 文件:
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()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
server: {
host: true,
port: 3000,
open: true,
proxy: {
// 字符串简写写法
'/api': 'http://localhost:8080',
// 选项写法
'/api-backend': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api-backend/, ''),
// 如果要代理 websockets
ws: true,
// 如果是 https 接口
// secure: false
},
// 正则表达式写法
'^/fallback/.*': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/fallback/, '')
},
// 使用 proxy 实例
'/api-custom': {
target: 'http://localhost:8080',
changeOrigin: true,
configure: (proxy, options) => {
// proxy 是 'http-proxy' 的实例
// 在这里,你可以进行更复杂的代理配置
}
}
}
}
})
在这个配置包含了几种不同的代理方式示例。
1.基础服务器配置:
server: {
host: true, // 监听所有地址
port: 3000, // 开发服务器端口
open: true, // 自动打开浏览器
}
2.基础服务器配置:
proxy: {
// 1. 简单配置 - 直接转发
'/api': 'http://localhost:8080',
// 2. 详细配置 - 带路径重写
'/api-backend': {
target: 'http://localhost:8080', // 目标服务器
changeOrigin: true, // 修改请求头中的 Origin
rewrite: (path) => path.replace(/^\/api-backend/, ''), // 路径重写
ws: true, // 支持 websocket
}
}
使用方式:
1.简单代理:
// 访问 /api/user 会被代理到 http://localhost:8080/api/user
fetch('/api/user')
2.带路径重写的代理:
// 访问 /api-backend/user 会被代理到 http://localhost:8080/user
fetch('/api-backend/user')
根据实际需求修改配置:
1.修改目标服务器地址:
'/api': 'http://your-backend-server.com'
2.添加多个代理路径:
proxy: {
'/api': 'http://api-server.com',
'/auth': 'http://auth-server.com',
'/ws': {
target: 'ws://socket-server.com',
ws: true
}
}
3.配置 HTTPS:
'/api': {
target: 'https://api-server.com',
secure: false // 如果是自签名证书
}
在使用的时候,根据实际的后端服务地址修改这些配置。
评论