Vite创建的React应用无法获取Express(PassportJS)发送的Cookie求助
是的,需要修改Vite配置文件来解决这个问题,核心原因是Vite开发服务器的代理默认不携带跨域请求凭证,而CRA的代理配置默认处理了这一点。
解决步骤:
修改Vite配置文件,添加带凭证的代理设置
在你的vite.config.js中添加server.proxy配置,显式开启withCredentials,确保请求转发时携带Cookie:import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], server: { proxy: { // 替换为你的后端API前缀,比如'/api' '/api': { target: 'http://localhost:3001', // 替换为你的后端服务地址 changeOrigin: true, withCredentials: true // 关键配置:允许跨域请求携带凭证 } } } })确保前端请求携带凭证
无论你用fetch还是axios发起认证请求,都要开启凭证携带:- 使用
fetch的示例:fetch('/api/auth/login', { method: 'POST', credentials: 'include', // 携带Cookie body: JSON.stringify(loginData), headers: { 'Content-Type': 'application/json' } }) - 使用
axios的示例:axios.post('/api/auth/login', loginData, { withCredentials: true })
- 使用
为什么CRA可以正常工作?
CRA的package.json中配置proxy字段后,内部的代理服务器会自动处理跨域凭证的转发,而Vite需要显式配置withCredentials才能实现相同效果。
额外确认(可选)
虽然你用CRA时后端正常,但可以再确认后端Cookie的配置:
- 确保
httpOnly、secure(生产环境)、SameSite属性设置合理,比如跨域场景下SameSite设为None并配合secure。
内容的提问来源于stack exchange,提问作者Max Vhanamane
相关产品推荐
相关产品推荐

