简体   繁体   中英

Nodejs Mysql: Accessing variable in another route

I'm building a simple e-wallet system that accepts user's phone number and query's the user's wallet from database and displays balance; I built a form that receives a phone number and uses the number to query the database for user id and uses that id to query his/her e-payment wallet id but i can't pass the wallet to a get request to render the wallet balance and username

router.post('/',function (req, res, next) {
  var sql = `SELECT UsrID FROM users WHERE UsrPhone =  ${req.body}`;
  var query = connection.queryValue(sql, function (err, userid) {
    if(err) throw err;
    console.log('User ID: ' + userid);

    var sql = `SELECT * FROM wallet WHERE UserID = ${userid}`;
    var query = connection.queryRow(sql, function (err, wallet) {
      if(err) throw err;
      console.log('WalletID: ' + wallet.WalletID);
      //send walletID to get route
      res.redirect('/wallet/:id');
    });
  });
});

router.get('/wallet/:id', function (req, res, next) {
  var sql = `SELECT * FROM wallet WHERE WalletID = ${wallet.WalletID}`;
  var query = connection.queryRow(sql, function (err, wallet) {
    if(err) throw err;
    res.render('wallet', {title: 'Wallet', wallet});
  });
});

but it doesn't seem to work

You didn't pass the current WalletID to the redirect route. You should pass the id to redirect URL like this:

res.redirect('/wallet/' + wallet.WalletID);

So, the wallet/:id can get the current WalletID and make the query base on that.

And you can run the query like this:

  var sql = `SELECT * FROM wallet WHERE WalletID = ${req.params.id}`;

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