跨域场景下Vue.js获取NestJS后端example.com域名Cookie的方法
问题场景
我用Vue.js开发的前端部署在localhost:5173,NestJS开发的后端部署在example.com域名下。后端通过Set-Cookie响应头给客户端发送授权信息,浏览器把这些Cookie存在example.com域名下,但Vue里用useCookie只能获取localhost域名的Cookie,拿不到example.com下的。
我的代码如下:
<template></template> <script setup lang="ts"> import { Account } from './types'; definePage({ meta: { layout: 'blank', isLoginProcess: true, }, }); const router = useRouter(); const route = useRoute(); const userStore = useUserStore(); const accessToken = useCookie('accessToken').value; if (accessToken) { userStore.accessToken = accessToken; useCookie('accessToken').value = null; } const account = useCookie<Account>('account').value; if (account) { userStore.account = JSON.parse(JSON.stringify(account)); useCookie('account').value = null; } if (route.query?.route) { router.push(`${route.query?.route}`); } else { router.push('/'); } </script>
已尝试的方案及问题
- 尝试让后端把Cookie的
domain改为localhost,但浏览器会弹出警告,且找不到Chrome里忽略该警告的设置; - 尝试从前端直接获取
example.com域名下的Cookie,但useCookie只支持同域获取。
可行解决方案
方案1:配置后端Cookie为跨域可携带(推荐)
浏览器同源策略禁止前端直接读取跨域Cookie,但只要后端正确配置Cookie属性,前端发起请求时浏览器会自动携带对应Cookie,无需手动读取。具体配置如下(以NestJS为例):
- 设置Cookie的
SameSite属性为None,同时必须开启Secure(仅HTTPS环境有效,开发环境可暂时关闭但生产必须开启); - 设置
domain为后端域名example.com,若需子域共享可设为.example.com; - 后端开启CORS,允许前端域名
http://localhost:5173,并配置credentials: true。
NestJS CORS配置示例:
// main.ts async function bootstrap() { const app = await NestFactory.create(AppModule); app.enableCors({ origin: 'http://localhost:5173', credentials: true, // 允许携带凭证 }); await app.listen(3000); } bootstrap();
NestJS设置Cookie示例:
// 登录接口中设置Cookie @Get('/login') async login(@Res({ passthrough: true }) res: Response) { res.cookie('accessToken', 'your-token-value', { domain: 'example.com', path: '/', secure: process.env.NODE_ENV === 'production', // 生产环境强制开启 sameSite: 'none', httpOnly: true, // 可选,防止XSS攻击,此时前端无法直接读取但请求会自动携带 }); }
前端请求时需开启withCredentials(以axios为例):
axios.get('https://example.com/api/user', { withCredentials: true });
方案2:通过后端接口间接获取Cookie
如果必须在前端拿到Cookie内容,可以在后端写一个接口,读取服务端的Cookie并返回给前端(后端属于同域,可直接读取自身设置的Cookie)。
NestJS接口示例:
@Get('/get-cookie') async getCookie(@Req() req: Request) { return { accessToken: req.cookies.accessToken, account: req.cookies.account, }; }
前端调用接口获取Cookie:
// Vue组件中 const fetchCookie = async () => { const res = await axios.get('https://example.com/api/get-cookie', { withCredentials: true }); if (res.data.accessToken) { userStore.accessToken = res.data.accessToken; } if (res.data.account) { userStore.account = res.data.account; } }; fetchCookie();
方案3:开发环境使用反向代理
开发阶段可在Vue项目中配置反向代理,将后端请求转发到localhost,让前后端处于同域,这样useCookie就能正常读取Cookie。
Vue Vite配置示例(vite.config.ts):
import { defineConfig } from 'vite'; import vue from '@vitejs/plugin-vue'; export default defineConfig({ plugins: [vue()], server: { proxy: { '/api': { target: 'https://example.com', changeOrigin: true, cookieDomainRewrite: 'localhost', // 将Cookie的domain重写为localhost }, }, }, });
此时前端请求改为/api/xxx,代理会转发到后端,浏览器会把Cookie存在localhost下,useCookie即可正常读取。
内容的提问来源于stack exchange,提问作者River990
相关产品推荐
相关产品推荐

