使用Axios无法从Express应用向Vue 3前端设置Session Cookie
复现步骤
- 下载前后端仓库,执行
npm i安装依赖 - 分别在两个仓库执行
npm run dev启动服务 - 访问
127.0.0.1:5173 - 点击Submit按钮,Chrome控制台有输出但Cookie未保存
需求
希望在浏览器中设置express-session的connect.sid Cookie,前端使用Vue3框架,已配置必要内容但Cookie仍无法保存,不清楚遗漏点。
前端代码(Vue3)
const submit = async () => { try { const { data } = await axios.post( "http://localhost:4050/new", { name: "Abeer" }, { withCredentials: true } ) console.log(data) } catch (error) { console.log(error) } }
后端代码(Express)
const express = require("express") const session = require("express-session") const cors = require("cors") const app = express() const PORT = process.env.PORT || 4050 app.use( cors({ origin: "http://127.0.0.1:5173", credentials: true, }) ) app.use(express.json()) app.use( session({ resave: false, saveUninitialized: false, secret: "session", cookie: { maxAge: 24 * 60 * 60 * 1000, sameSite: "none", secure: false, }, }) ) // save a name as a cookie app.post("/new", async (req, res) => { try { const name = req.body.name req.session.name = name res.send({ message: "saves" }).status(201) } catch (error) { console.log(error) } }) app.get("/name", async (req, res) => { try { console.log(req.session.name) res.send({ message: req.session.name }) } catch (error) { console.log(error) } }) app.listen(PORT, () => console.log(`Server is running on ${PORT}`))
问题原因及修复方案
1. 请求域名不一致
前端请求用的是http://localhost:4050/new,但后端CORS配置的origin是http://127.0.0.1:5173,浏览器会把localhost和127.0.0.1视为不同域名,导致Cookie无法跨域保存。
修复:将前端请求地址改为http://127.0.0.1:4050/new,和后端CORS配置的域名保持一致。
2. SameSite与Secure配置冲突
当sameSite: "none"时,浏览器强制要求secure: true(仅HTTPS环境生效),但你当前设置secure: false,浏览器会直接拒绝保存Cookie。
修复:
开发环境下修改session配置:
cookie: { maxAge: 24 * 60 * 60 * 1000, sameSite: "lax", // 改为lax或strict secure: false, }
生产环境启用HTTPS后,再设置sameSite: "none"和secure: true。
3. 响应状态码设置顺序错误
后端代码中res.send({ message: "saves" }).status(201)写法错误,res.send()会直接结束响应,后续的status()无法生效,导致状态码不符合预期。
修复:
res.status(201).send({ message: "saves" })
验证
按上述修复后重启服务,点击Submit按钮,查看Chrome开发者工具的Application -> Cookies -> 127.0.0.1:4050,即可看到connect.sid Cookie已保存。
内容的提问来源于stack exchange,提问作者Abeer
相关产品推荐
相关产品推荐

