我目前正在构建一个快速应用程序,请求模块从API获取数据。但是,我想将此数据传递给res.render函数而不创建全局变量。即使在创建全局时,它也会首先更新控制台.log,然后才会更新网站上的视图。我只是想知道如何执行此操作并将数据传递到res.render函数。谢谢。
var pounds = {};
exports.index = function(req, res) {
request(options, function(err, res, body) {
if (!err && res.statusCode === 200) {
let info = JSON.parse(body);
pounds = ("£"+info.GBP);
console.log(pounds)
};
});
res.render('pages/index', {british: pounds});
答案 0 :(得分:0)
只需将您的呼叫转移到内部回调内的res.render
,并使用本地变量。另外,请确保不要使用内部res
遮住外部response
(我已将其重命名为内部的exports.index = function(req, res) {
request(options, function(err, response, body) {
if (!err && response.statusCode === 200) {
let info = JSON.parse(body);
let pounds = "£" + info.GBP;
// Local -------^
res.render('pages/index', { // Moved to within
british: pounds // the inner
}); // callback
};
});
};
)。
__()