简体   繁体   中英

Nodejs global variable

I have a variable called username in a post route within my node.js server-side code (accessed through a form submission) and I would like to use this same variable in another post route.

app.post("/login", function(req, res) {
    var username = req.body.username;
    ...
});
//Another app.post route

Is there any way I could do this?

Best solution is that first you initialize global variable in express app

app.use(function (req, res, next) {
    res.locals.username = "";
    next();
});

set this variable in post route

app.post("/login", function(req, res) {
 global.username = req.body.username;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM