我正在尝试使用express,nuxtjs和express-session来实现登录功能。只要我不刷新页面,一切都会按预期进行。
重新加载页面后,cookie中将不再存储任何内容。
server / index.js
app.use(cors({
origin: ['http://localhost:3000'],
methods: ['GET', 'POST', 'DELETE', 'PUT', 'PATCH'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Accept', 'Origin'],
exposedHeaders: 'Authorization',
credentials: true
}))
app.use(session({
secret: process.env.JWT_SECRET,
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: false,
secure: false,
maxAge: 1000 * 60 * 60 * 24 * 30 // ~1 month
},
store: new MongoStore({
mongooseConnection: mongoose.connection,
touchAfter: 24 * 3600
})
}))
store / index.js
export const actions = {
async nuxtServerInit ({ commit }, { req }) {
console.log(req.session) // Output2
console.log('user: ' + req.session.user, req.session.token) //Output3
if (req.session.user && req.session.token) {
commit('auth/SET_USER', req.session.user)
commit('auth/SET_TOKEN', req.session.token)
}
}
}
/*
Output2 (no user or token included)
Session {
cookie:
{ path: '/',
_expires: 2019-09-19T19:10:44.967Z,
originalMaxAge: 2592000000,
httpOnly: false,
secure: false } }
Output3
user: undefined undefined
*/
server / api / users.js
// POST /users/login
router.post('/users/login', async (req, res) => {
try {
const body = _.pick(req.body, ['email', 'password']);
const user = await User.findByCredentials(body.email, body.password);
const token = await user.generateAuthToken();
req.session['token'] = 'Bearer ' + token;
req.session['user'] = user;
console.log(req.session.token, req.session.user); //Output1
res.set('Authorization', 'Bearer ' + token);
res.send(user);
} catch (err) {
res.status(401).json({ message: "Incorrect credentials" });
}
});
/*
Output1 (shortened for readibility)
Bearer eyJhbGciOiJIUzI1NiI.... {
_id: 5d5c45c273bad91bfb26fc3d,
name: 'username',
slug: 'username',
email: 'e@mail.com',
password:
'$2a$10$SCrA8L...',
tokens:
[ { _id: 5d5c467673bad91bfb26fc3f,
access: 'auth',
token:
'eyJhbGciOiJIUzI1NiI.....' } ],
createdAt: 2019-08-20T19:10:58.770Z,
updatedAt: 2019-08-20T19:13:58.415Z,
__v: 2 }
*/
nuxt.config.js
axios: {
prefix: '/api',
credentials: true,
https: false
}
Mongodb商店集合
{
"_id" : "-MuJ-xvgHx_K6-tUQ521JnGVSRuj5rbG",
"expires" : ISODate("2019-09-23T12:35:43.663Z"),
"lastModified" : ISODate("2019-08-24T12:35:43.667Z"),
"session" : "{\"cookie\":{\"originalMaxAge\":2592000000,\"expires\":\"2019-09-23T12:35:43.663Z\",\"secure\":false,\"httpOnly\":false,\"path\":\"/\"},\"token\":\"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZDYwZDczMDQ0MGZiZjBmMjA2MjdiZTUiLCJhY2Nlc3MiOiJhdXRoIiwiaWF0IjoxNTY2NjUwMTQzfQ.94KQE8WilvIQg1ahInLDcqixpr2zEZFmERmFSGPZw8I\",\"user\":{\"_id\":\"5d60d730440fbf0f20627be5\",\"email\":\"sc@sc.de\",\"name\":\"schwesi\",\"slug\":\"schwesi\"}}"
}
DEBUG =页面重新加载时的express-session输出:
express-session fetching NgTNXp86jWyzqEIcvgsNNjwwpHgy502r +1ms
express-session session found +1ms
express-session touching +0ms
express-session split response +0ms
express-session session found +1ms
express-session touching +1ms
express-session split response +0ms
express-session touched +0ms