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

Axios仅在初始路由携带Session Cookie,其他路由失效求助

问题:跨路由后Express Session无法识别用户信息

项目背景

我正在开发React前端+Node.js后端的项目,前端用Axios发起请求,后端通过Express+express-session创建Session Cookie,用于用户验证、路由权限控制及信息展示。

问题现象

仅在/login(初始路由)能获取Session中的用户信息;用户登录跳转至其他路由(如/hr)时,虽浏览器开发者工具可见Cookie,但后端req.session.user始终为undefined。我在/login、/app、/register三个路由的useEffect中均发起如下测试请求,仅在/login路由能返回包含user的Session对象:

Axios.get('http://' + urlCustom + ':' + portCustom + '/orders',{withCredentials:true}).then((response)=> { console.log(response); })

已尝试方案

  • 设置Axios请求的{withCredentials:true}及全局Axios.defaults.withCredentials = true
  • 调整express-session的Cookie参数(sameSite、secure、httpOnly等),但问题仍未解决

关键代码

前端Login.js关键代码

const [urlCustom, setServUrlCustom] = useState('x.x.x.x');//实际为真实IP,此处隐藏
const [portCustom, setServPortCustom] = useState('3001');
const navigate = useNavigate();
Axios.defaults.withCredentials = true;

useEffect(()=>{
  Axios.get('http://' + urlCustom + ':' + portCustom + '/orders',      
  {withCredentials:true}).then((response)=> {
    console.log(response);
  })
})

其他路由请求代码与上述一致。

后端index.js关键代码

const express = require("express");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const app = express();

const session = require("express-session");

app.use(session({
    key: "userId",
    secret: "subscribe",
    resave: false,
    saveUninitialized: false,
    cookie: {
      httpOnly: false,
      expires: 60 * 60 * 24 * 1000,
      secure: false,
      sameSite: false,
    },
  })
);//Cookie参数已尝试多种配置,欢迎提供建议

app.use(cors({
  origin:["http://192.168.1.9:3000"],
  methods:["GET", "POST"],
  credentials: true
}));

app.use(cookieParser());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get("/orders", (req,res) => {
  console.log(req.session);
  console.log("hola")
  res.send("req.session");
})

后端Session创建接口代码

app.get("/api/loginCheck", (req, res) => {
  let user = req.query.nombreUser;
  let passw = req.query.passUser;
  let encryptedPass = encyptPass(passw); //自定义密码加密函数
    sql.connect(sqlConfig, function (err) {
    
      if (err) {
        console.log("the sqlconnect error is " + err);
      }
      var request = new sql.Request();

      request.query(
        "select * from testusers.dbo.userslogin where nameuser = '" + user + "' and passuser = '"+ encryptedPass + "'",
        function (err, records) {
          if (err) {
            console.log("login error is " + err);
          } else {
            
            if (records.rowsAffected[0] == 0) {
              res.send("User or Password are incorrect.");
            } else {
                req.session.user = records.recordset[0];
                res.send(req.session.user);
            }
          }
        }
      );
    });  
});

排查与解决方案建议

  1. 指定Cookie的Domain和Path
    当前session cookie未设置domain和path,浏览器可能将Cookie绑定到具体端口或路径。添加以下参数确保Cookie在所有路径下生效:

    cookie: {
      // ...原有参数
      domain: '192.168.1.9', // 替换为后端实际IP
      path: '/'
    }
    
  2. 验证Axios请求URL一致性
    检查其他路由中urlCustom和portCustom是否与/login路由完全一致,避免因IP/端口拼写错误导致请求发送到不同地址,无法携带正确Cookie。

  3. 调整Session保存参数
    尝试修改saveUninitialized和resave参数,确保Session被正确持久化:

    app.use(session({
      // ...原有参数
      resave: true,
      saveUninitialized: true
    }))
    
  4. 改用数据库存储Session
    默认内存存储在开发环境可能出现Session丢失问题,安装express-mysql-session将Session存储到数据库:

    const MySQLStore = require('express-mysql-session')(session);
    const sessionStore = new MySQLStore(sqlConfig); // 复用你的数据库配置
    
    app.use(session({
      // ...原有参数
      store: sessionStore
    }))
    
  5. 优化CORS配置
    确保前端所有请求的Origin都被允许,可改用动态匹配逻辑:

    app.use(cors({
      origin: function(origin, callback) {
        const allowedOrigins = ['http://192.168.1.9:3000'];
        if (!origin || allowedOrigins.includes(origin)) {
          callback(null, true);
        } else {
          callback(new Error('Not allowed by CORS'));
        }
      },
      credentials: true
    }));
    
  6. 禁用浏览器隐私模式测试
    隐私模式会限制Cookie跨路径携带,切换到正常浏览器模式验证是否恢复正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 04:34:57