我从查询中获取结果并将其存储在一个变量中,该变量将通过渲染发送,但是未给出错误变量的问题。请帮帮我。如果可能,请更正代码。
router.get('/create',(req,res)=>{
connection.query('SELECT * FROM purchases',function(error,results,fields){
var voucher = 'PH-'+results.length+1;
connection.query('SELECT * FROM vendors where wid=?',[req.session.w_id],function(err,res,f){
var vendors=res;
connection.query('SELECT * FROM products where wid=?',[req.session.w_id],function(er,r,fi){
var products=r;
})
})
});
res.render('purchase_create',{voucher:voucher,vendors:vendors,products:products});
});
错误是:未定义凭证
答案 0 :(得分:1)
voucher
仅在您传递给connection.query
的回调函数中可用,与vendors
和products
相同。您必须将res.render
调用移到最内层的函数中才能完成此工作:
router.get('/create', (req, res) => {
connection.query('SELECT * FROM purchases', function (error, results, fields) {
var voucher = 'PH-' + results.length + 1;
connection.query('SELECT * FROM vendors where wid=?', [req.session.w_id], function (err, res, f) {
var vendors = res;
connection.query('SELECT * FROM products where wid=?', [req.session.w_id], function (er, r, fi) {
var products = r;
res.render('purchase_create', { voucher: voucher, vendors: vendors, products: products });
});
});
});
});
答案 1 :(得分:0)
连接对象的“查询”方法需要一个回调函数,该函数将在以下三个事件之一触发时执行:错误,字段,结果,这里分别用参数err,字段和行表示。
router.get('/create', (req, res) => {
connection.query('SELECT * FROM purchases', function (error, results, fields)
{
if (error) throw error;
var voucher = 'PH-' + results.length + 1;
connection.query('SELECT * FROM vendors where wid=?', [req.session.w_id], function (err, res, f)
{
if (err) throw err;
var vendors = res;
connection.query('SELECT * FROM products where wid=?', [req.session.w_id], function (er, r, fi)
{
if (er) throw er;
var products = r;
res.render('purchase_create', { voucher: voucher, vendors: vendors, products: products });
});
});
});
});