我试图解决这个问题很长一段时间。我尝试使用快速cookie会话进行cookie会话并在前面做出反应。 Cookie应该在我的req.session对象中,但它是空的。
这是我的代码:
const cookieSession = require('cookie-session');
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const keys = require('./config');
app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.set('trust proxy', 1);
app.use(cookieSession({
name: 'session',
maxAge: 3000000,
keys: ['key1', 'key2']
}))
app.get('/t', function (req, res) {
// here I'm expecting to get cookie object
res.send(req.session);
})
require('./routes/tasksRoutes')(app);
require('./routes/checkAnswers')(app)
app.listen(5000);
你能帮助我吗?为什么我得到空物? 谢谢你们!
答案 0 :(得分:0)
你需要设置cookie,你所做的就是配置它,现在你需要设置它才能使用它
const cookieSession = require('cookie-session');
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const keys = require('./config');
app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.set('trust proxy', 1);
app.use(cookieSession({
name: 'session',
maxAge: 3000000,
keys: ['key1', 'key2']
}))
// now when you'd hit this URL your user will have a cookie attached to it.
app.get('/s', function (req, res) {
res.cookie('cookieName', 'cookieValue')
});
app.get('/t', function (req, res) {
// you'd be able to see your cookie object here after hitting '/s' API
// here I'm expecting to get cookie object
res.send(req.session);
})
require('./routes/tasksRoutes')(app);
require('./routes/checkAnswers')(app)
app.listen(5000);