You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue+Express全栈开发时如何解决Cookie跨域存储与传递问题?

Vue+Express开发阶段跨域Cookie问题解决方案

问题场景

前端Vue(Vite)运行在5173端口,后端Express运行在3000端口,开发阶段跨域导致httpOnly Cookie无法正常存储、传递;生产环境通过后端app.get("*")托管前端构建产物可解决,但开发时频繁构建效率极低,不想采用这种方式。


可行解决方案

1. Vite配置请求代理(最推荐)

通过Vite的代理功能,将前端请求转发到后端,让浏览器认为请求是同域发起,自动处理Cookie:

在vite.config.js中添加代理配置:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        // 若后端接口无/api前缀,可通过rewrite去除前端请求的前缀
        // rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  }
})

前端请求时直接用/api/xxx替代http://localhost:3000/api/xxx,此时浏览器会判定请求来自同域,Cookie会自动存储并在后续请求中携带。

2. 后端配置CORS允许跨域凭证

如果不想用代理,可通过后端CORS配置+前端请求开启凭证的方式解决:

后端Express配置

使用cors中间件,明确允许前端域名携带凭证:

const express = require('express');
const cors = require('cors');
const app = express();

// 配置CORS,允许前端5173端口跨域请求并携带凭证
app.use(cors({
  origin: 'http://localhost:5173',
  credentials: true
}));

// 设置Cookie时,注意配置SameSite和Secure(开发环境Secure设为false)
app.get('/login', (req, res) => {
  res.cookie('token', 'your_token_value', {
    httpOnly: true,
    sameSite: 'lax', // 开发环境用lax即可,生产环境可根据情况调整
    secure: false, // 开发环境http协议下设为false,生产环境https设为true
    maxAge: 24 * 60 * 60 * 1000
  });
  res.send('Login success');
});

前端请求配置

以Axios为例,开启携带凭证:

import axios from 'axios';

axios.defaults.withCredentials = true;

// 发起请求
axios.get('http://localhost:3000/login')
  .then(res => console.log(res))
  .catch(err => console.error(err));

3. 临时统一端口(无需构建)

如果上述两种方式都不想用,可通过工具同时启动前后端,并配合代理实现无构建跨域Cookie正常工作。比如用concurrently同时启动脚本:

在项目根目录的package.json中添加脚本:

{
  "scripts": {
    "dev": "concurrently \"npm run dev:frontend\" \"npm run dev:backend\"",
    "dev:frontend": "vite",
    "dev:backend": "node server.js"
  }
}

执行npm run dev即可同时启动前后端,配合Vite代理配置实现Cookie正常流转。


内容的提问来源于stack exchange,提问作者icedcacao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 22:40:05