我试图在一种POST方法中设置Express会话,然后在应用程序中的另一种方法中访问它。
我的应用设置:
const expressSession = require('express-session');
const app = express();
app.use(bodyParser.urlencoded({ extended: false}))
app.use(bodyParser.json());
app.use(expressValidator());
app.use(expressSession({
secret: 'max',
saveUninitialized: false,
resave: false,
}))
app.use(cors());
我要在其中设置会话用户名的登录端点:
app.post('/login', (req, response) => {
let username = req.body.username;
let password = req.body.password;
User.find({userName:username}, 'userName password', function(err, docs){
if(err) {response.send(err)}
if (docs.length === 0) {
response.send(JSON.stringify({'message': 'Wrong username or password'}))
} else {
bcrypt.compare(password, docs[0].password, (err, result) => {
if(err) response.send(err);
if(result) {
console.log('finding the username', docs[0].userName);
req.session.username = docs[0].userName;
req.session.save((err) => {
if (err) {
console.log('session save error')
} else {
console.log(req.session);
}
})
jwt.sign({password: docs[0].password}, 'secretkey', (err, token) => {
if(err) {response.send(err);
} else {
response.send(JSON.stringify({'token': token, 'success': true}));
}
})
}
})
}
})
});
我要访问req.session.username的Post方法:
app.post('/upload', imageUpload.single('myFile'), (req, res) => {
console.log(req.file);
console.log(req.session.username);
let savedUser = req.session;
console.log(savedUser.id);
res.end();
})
'/ upload'端点中的用户名总是返回未定义状态,但是登录端点中的console.log正是我想要的。如何从另一个端点访问该会话?