在express服务器的成员变量(类实例)之间传递数据的体系结构/方法可以通过以下几种方式实现:
app.get('/route1', (req, res, next) => {
req.customData = 'Hello World';
next();
});
app.get('/route2', (req, res) => {
console.log(req.customData); // 输出 'Hello World'
res.send('Data received');
});
let customData = 'Hello World';
app.get('/route1', (req, res, next) => {
customData = 'Modified Data';
next();
});
app.get('/route2', (req, res) => {
console.log(customData); // 输出 'Modified Data'
res.send('Data received');
});
express-session
中间件来处理会话。例如:const session = require('express-session');
app.use(session({
secret: 'secret-key',
resave: false,
saveUninitialized: true
}));
app.get('/route1', (req, res, next) => {
req.session.customData = 'Hello World';
next();
});
app.get('/route2', (req, res) => {
console.log(req.session.customData); // 输出 'Hello World'
res.send('Data received');
});
总结起来,以上是在express服务器的成员变量(类实例)之间传递数据的几种常见方法。具体使用哪种方法取决于应用的需求和场景。
领取专属 10元无门槛券
手把手带您无忧上云