生产环境下Vite React后端代理及Google OAuth回调问题排查
解决方案:让Google OAuth回调直达后端并解决缓存问题
完全可行,以下是具体解决步骤:
1. 后端路由优先级配置(核心)
确保后端先处理所有/api前缀的请求,再返回React静态文件,避免SPA路由捕获回调请求。以Express为例:
const express = require('express'); const path = require('path'); const app = express(); // 第一步:挂载所有API路由(包含Passport的Google回调) app.use('/api', require('./routes/api')); // 第二步:处理静态资源,仅非/api请求返回React的index.html app.use(express.static(path.join(__dirname, 'client/build'))); // 第三步:SPA路由 fallback,排除/api请求 app.get('*', (req, res) => { if (!req.path.startsWith('/api')) { return res.sendFile(path.join(__dirname, 'client/build', 'index.html')); } // 未匹配的API请求返回404 res.status(404).json({ error: 'API endpoint not found' }); });
2. 解决浏览器缓存导致的空白页问题
浏览器缓存了React的index.html,即使后端关闭也会显示空白页。需要给index.html设置严格的缓存控制头,禁止强缓存:
// 修改静态资源服务配置,添加缓存控制 app.use(express.static(path.join(__dirname, 'client/build'), { // 静态资源(js、css、图片等)带哈希值,可设置长缓存 maxAge: '30d', setHeaders: (res, filePath) => { if (path.basename(filePath) === 'index.html') { res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate'); res.setHeader('Pragma', 'no-cache'); res.setHeader('Expires', '0'); } } }));
3. 确认Google OAuth配置正确性
在Google开发者控制台中,授权重定向URI必须填写后端的完整回调地址,例如:https://your-production-domain.com/api/auth/google/callback
绝对不能填前端地址,否则回调请求会直接到前端,无法触发后端的Passport逻辑。
4. 生产环境避免依赖Vite代理
Vite的proxy配置仅在开发环境生效,生产环境是构建后的静态文件,必须通过后端(或反向代理如Nginx)来分流/api请求。如果用Nginx反向代理,配置示例如下:
server { listen 80; server_name your-domain.com; # 优先转发/api请求到后端服务 location /api { proxy_pass http://localhost:3000; # 后端服务端口 proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } # 处理前端静态资源,对index.html禁用缓存 location / { root /path/to/react/build; try_files $uri $uri/ /index.html; if ($request_uri = '/') { add_header Cache-Control "no-cache, no-store, must-revalidate"; add_header Pragma "no-cache"; add_header Expires "0"; } } }
内容的提问来源于stack exchange,提问作者LUKER
相关产品推荐
相关产品推荐

