简体   繁体   中英

Make global copy of local variables in Nodejs

I have extracted a username, password and another password with express like this:

var urlencodedParser = bodyparser.urlencoded({extended: false});
app.post('/', urlencodedParser, function(req, res) {
    console.log(req.body);
    var un = req.body.username;
    var pw1 = req.body.pwd1;
    var pw2 = req.body.pwd2;
});

I then want to do something with the new variables I have created. How can I use them outside of this function?

You can either make them global or pass them to the next function

var un, pw1, pw2
var urlencodedParser = bodyparser.urlencoded({extended: false});
app.post('/', urlencodedParser, function(req, res) {
    console.log(req.body);
    un = req.body.username;
    pw1 = req.body.pwd1;
    pw2 = req.body.pwd2;
});

Or passing them on:

var urlencodedParser = bodyparser.urlencoded({extended: false});
app.post('/', urlencodedParser, function(req, res) {
    console.log(req.body);
    doSomething(req.body.username, req.body.pw1, req.body.pw2);
});

function doSomething(un, pw1, pw2) {
    ...
}

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