[英]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
我建立了一个接收电话号码的表格,并使用该号码查询数据库中的用户ID,并使用该ID查询他/她的电子支付钱包ID,但是我无法将钱包传递给获取请求以呈现钱包余额和用户名
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. 您没有将当前的
WalletID
传递给重定向路由。 You should pass the id to redirect URL like this: 您应该传递id来重定向URL,如下所示:
res.redirect('/wallet/' + wallet.WalletID);
So, the wallet/:id
can get the current WalletID
and make the query base on that. 因此,
wallet/:id
可以获取当前的WalletID
并在此基础上进行查询。
And you can run the query like this: 您可以像这样运行查询:
var sql = `SELECT * FROM wallet WHERE WalletID = ${req.params.id}`;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.