我正在学习编码,我正在为我的业务构建一个应用程序。我在show route上传递url参数时遇到问题。
我正在使用Node.js和MySQL。该路径显示7个不同的报告,我将每个报告分成单独的js文件,导出功能并调用show route上的函数来显示页面。问题是我对每个函数的MySQL查询都不是动态的,因为我无法访问每个单独的js文件中的url参数。
我已尝试在routes.js页面上创建一个函数,但请求未定义,因为每个req都在一个路由中声明。我也尝试在各个js文件上使用$ {req.params.id},但req仍未定义。
这是我的节目路线:
router.get("/clients/:id/reports/monthlyreport/:marketplace/:month", function (req, res){
monthToMonth(function(arr){
topSkuUnitsMonth(function(arr1){
topSkuCogsMonth(function(arr2){
productMix(function(arr3){
ltmCogs(function(arr4){
topSkuCogsLTM(function(arr5){
topSkuUnitsLTM(function(arr6){
quarterComparison(function(arr7){
res.render("reports/show", {current: arr, math: math, units: arr1, cogs: arr2, mix: arr3, totals: arr4, yearCOGS: arr5, yearUnits: arr6, quarter: arr7});
})
})
})
})
})
})
})
})
});
这是monthToMonth函数:
module.exports = function monthToMonth(callback){
var q = `select
t1.client_id,
DATE_FORMAT(t1.period, '%Y-%m') as period,
ROUND(t1.shipped_COGS,0) as shipped_COGS_current_month,
t1.shipped_units as shipped_units_current_month,
t1.product_title as product_title_current_month,
t1.asin as asin_current_month,
ROUND(t2.shipped_COGS,0) as shipped_COGS_past_month,
t2.shipped_units as shipped_units_past_month,
t2.product_title as product_title_past_month,
t2.asin as asin_past_month
from all_months_ca t1
join all_months_ca t2 on t1.asin = t2.asin
where t1.client_id = 1 && t2.client_id = 1 && (t1.shipped_units > 0 || t2.shipped_units > 0) && (DATE_FORMAT(t1.period, '%Y-%m') = '2019-05' && DATE_FORMAT(t2.period, '%Y-%m') = '2019-04')
group by t1.asin
order by shipped_COGS_current_month DESC;`
db.query(q, function(err, foundData){
if(err) throw err;
callback (foundData)
})
}
MySQL查询当前在WHERE子句中有句点和client_id硬编码,但是我需要url参数来使查询动态化。如何将参数传递给这些js。文件?
为什么不在每个函数中传递req对象。
module.exports = function monthToMonth(req, callback){
var q = `select
t1.req.params.id,
DATE_FORMAT(t1.period, '%Y-%m') as req.params.month,
ROUND(t1.shipped_COGS,0) as shipped_COGS_current_month,
t1.shipped_units as shipped_units_current_month,
t1.product_title as product_title_current_month,
t1.asin as asin_current_month,
ROUND(t2.shipped_COGS,0) as shipped_COGS_past_month,
t2.shipped_units as shipped_units_past_month,
t2.product_title as product_title_past_month,
t2.asin as asin_past_month
from all_months_ca t1
join all_months_ca t2 on t1.asin = t2.asin
where t1.client_id = 1 && t2.client_id = 1 && (t1.shipped_units > 0 || t2.shipped_units > 0) && (DATE_FORMAT(t1.period, '%Y-%m') = '2019-05' && DATE_FORMAT(t2.period, '%Y-%m') = '2019-04')
group by t1.asin
order by shipped_COGS_current_month DESC;`
db.query(q, function(err, foundData){
if(err) throw err;
callback (foundData)
})
并调用此函数像 -
router.get("/clients/:id/reports/monthlyreport/:marketplace/:month", function (req, res){
monthToMonth(req, function(arr){
// call remaining function in same way.
topSkuUnitsMonth(req, function(arr1){
}) })