Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

express-session获取session字段是undefined

我使用express+node.js搭建了一个项目,但是使用express-session插件设置session字段时却出现了问题,在A文件的一个接口里设置了session字段,在B文件里获取的值却是undefined
app.js

const session = require("express-session");
router.use(
  session({
    secret: "keyboard cat",
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true, cookie: { maxAge: 20 * 60 * 1000 } }
  })
);

/routes/account.js

const session = require("express-session");
router.use(
  session({
    secret: "keyboard cat",
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true, cookie: { maxAge: 20 * 60 * 1000 } }
  })
);


router.post("/api_login",(req,res)=>{
    req.session.user="测试"
})

/routes/index.js

router.get("/api_index",(req,res)=>{
    console.log(req.session.user);//undefined
    res.render("index",{title:"首页"})
})

在上面的代码里我不仅在app.js文件里挂载了express-session插件,在routes目录下的路由文件里又将express-session挂载在了router下,这是因为我发现挂载到app.js文件里,在路由文件里设置的时候会报错,原因是找不到这个session插件,body-parser插件也是一样的情况,令我很疑惑,app.js是全局文件,一年前我用相同的框架和插件搭建了一个管理系统,就是只将插件挂载到了app.js文件里,无论是body-parser还是express-session存储都是正常使用的,但是现在新的项目为什么不行了,为什么设置的session字段获取到的是undefined?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

解决了,我换成了cookie-session就可以正常设置以及获取字段了,我想着是不是express-session不兼容最新的express框架


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...