我的cookie完全签名,但是我用req.signedCookie.sessionID
显示undefined
购物车路线文件:
router.post('/add-to-cart/:productID', async (req, res) => {
console.log(req.signedCookies.sessionID); // undefined
});
这是开发人员工具中我的cookie的图像:
Cookie in google chrome developer tool
这是我的server.js文件
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cors());
require('dotenv').config();
const port = process.env.PORT || 7000;
// Import Routes
const cartRoute = require('./routes/cart');
// Access localhost mongodb with mongoose
const url = process.env.DB_URL;
mongoose.connect(
url,
{
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
},
() => {
console.log('Connect to database success!');
}
);
// Middleware
app.use(cookieParser(process.env.SESSION_SECRET));
app.use(express.json());
app.use(express.static('public'));
const sessionMiddleware = require('./middleware/session');
// Route middelware
app.use(sessionMiddleware);
app.use('/api/cart', cartRoute);
// Server listen at port ?
app.listen(port, () => {
console.log(`Server is running at port: ${port}`);
});
这是我签名Cookie的会话中间件文件
module.exports = async (req, res, next) => {
if (!req.signedCookies.sessionID) { // Check if cookie exists, if not we will create new cookie with name: sessionID
const sessionID = shortID.generate();
res.cookie('sessionID', sessionID, {
signed: true,
expires: new Date(Date.now() + 8 * 3600000)
});
}
next();
};