📚 目录
- 本地开发环境:Vite 代理配置
- 生产部署环境:Nginx 反向代理配置
- 常见跨域问题说明
- 实战场景配置示例
- 常见错误及排查方法
- 推荐最佳实践
1️⃣ 本地开发环境:Vite 的反向代理配置
在 Vue3 项目中,使用 Vite 提供的 server.proxy
功能,可以实现接口请求的本地代理,解决开发环境的跨域问题。
🛠 配置位置:
文件:vite.config.js
或 vite.config.ts
✍ 示例配置:
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [vue()],
server: {
port: 3000,
open: true,
proxy: {
'/api': {
target: 'http://localhost:8080', // 后端地址
changeOrigin: true, // 修改 origin 头
rewrite: path => path.replace(/^\/api/, '') // 重写路径
}
}
}
});
✅ 效果说明:
http://localhost:3000/api/user
将代理为http://localhost:8080/user
changeOrigin: true
会将请求头中的 Host 替换为目标地址(防止跨域拒绝)
2️⃣ 生产部署环境:Nginx 的反向代理配置
Vite 构建后会生成静态文件(dist/
目录),Nginx 可用来托管前端资源并代理接口请求。
🔧 示例配置文件:
server {
listen 80;
server_name example.com;
root /var/www/my-vue-app/dist;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
# 接口代理配置
location /api/ {
proxy_pass http://localhost:8080/; # 代理到后端
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
📌 注意事项:
try_files
目的是为了解决 SPA 前端路由刷新 404 问题proxy_pass
路径要注意/api/
的尾部是否保留,保持路径一致性- 配合后端配置 CORS,或通过 Nginx 实现同源请求绕开跨域限制
3️⃣ 常见跨域问题说明
问题描述 | 解决方法 |
---|---|
接口返回 CORS 错误 | 本地开发用 vite.config.js 代理 + changeOrigin: true |
生产环境跨域 | 前后端部署在同一域名下(代理路径分离即可) |
OPTIONS 预检请求失败 | 确保后端允许 OPTIONS 请求;或用 Nginx 代理 |
4️⃣ 实战场景配置示例
🌐 场景 1:代理后端为 Spring Boot,端口为 8080
Vite 配置:
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: path => path.replace(/^\/api/, '')
}
}
Nginx 配置:
location /api/ {
proxy_pass http://localhost:8080/;
}
🌐 场景 2:后端部署在远程服务器 api.myapp.com
Vite:
proxy: {
'/api': {
target: 'https://api.myapp.com',
changeOrigin: true,
secure: false,
rewrite: path => path.replace(/^\/api/, '')
}
}
Nginx:
location /api/ {
proxy_pass https://api.myapp.com/;
}
5️⃣ 常见错误及排查方法
错误日志 / 现象 | 排查建议 |
---|---|
404 Not Found (前端刷新页面跳转) | 是否使用 try_files $uri $uri/ /index.html; |
跨域错误:No ‘Access-Control-Allow-Origin’ | 检查是否配置代理或后端是否启用 CORS |
代理路径失效 | 确认 Vite 中是否正确重写路径 |
Nginx 中静态文件未加载 | 检查 root 路径是否指向 dist/ |
6️⃣ 推荐最佳实践
- 本地开发使用
/api
前缀作为代理分流路径,避免和真实路径冲突 - 生产环境前后端使用同源不同路径(如
/api/
与/app/
),避免 CORS - 后端不应处理跨域逻辑,前端代理/Nginx 应统一解决
- 构建后前端文件部署到
/dist
,由 Nginx 统一托管,性能最佳
🔗 参考链接(出站链接)
如需我为你的项目生成一个完整的 Vite 与 Nginx 配置模板文件,或者你有特定部署场景(如 HTTPS、多服务代理、Docker 环境等),欢迎继续提问。
发表回复