如何在express的中間件中使用request請(qǐng)求接口數(shù)據(jù)或進(jìn)行數(shù)據(jù)庫(kù)查詢?例如有個(gè) url = "http://127.0.0.1/shops/××××/"我想在express中使用中間件先給每一個(gè)shop路徑的請(qǐng)求添加一些公共的數(shù)據(jù),并傳遞給后面的處理函數(shù),app.use('/shops', function (req, res, next) { res.locals["title"] = "New Page Title"; next();});這樣每一個(gè)經(jīng)過(guò)shops的請(qǐng)求都會(huì)被添加一個(gè)title,但是如果我的數(shù)據(jù)是從通過(guò)request異步請(qǐng)求后端接口,或者使用mysql請(qǐng)求, 這時(shí),數(shù)據(jù)都從對(duì)應(yīng)的callback中返回,無(wú)法進(jìn)行res.locals賦值。app.use('/shops', function (req, res, next) {res.locals["title"] = "New Page Title"; var shop_url = "http://127.0.0.1/api/shop/";request(shop_url, function (err, resonse, body) { res.locals.info = body; //異步賦值失敗})console.log(res.locals.info); // undefinednext();});應(yīng)該怎么做才能獲得callback中的的數(shù)據(jù)呢/?
如何在express的中間件中使用request請(qǐng)求接口數(shù)據(jù)或進(jìn)行數(shù)據(jù)庫(kù)查詢
慕容708150
2018-12-18 21:22:13