【问题标题】:Accessing variables without using global express request module在不使用全局快速请求模块的情况下访问变量
【发布时间】:2017-12-31 23:32:06
【问题描述】:

我目前正在构建一个快速应用程序,其请求模块从 API 获取数据。但是,我想将此数据传递给 res.render 函数而不创建全局变量。即使在创建全局时,它也会先 console.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});

【问题讨论】:

    标签: json express request


    【解决方案1】:

    只需将您对res.render 的调用移动到 内部回调中,并使用局部变量。还要确保不要用内部的 res 遮盖外部的 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
            };
        });
    };
    

    【讨论】:

    • @t-j-crowder 感谢您的回答 Tj,但是它会抛出此错误 TypeError: res.render is not a function
    • @zak: 啊,我没注意到你用内部的res 遮蔽了你的外部res。只需重命名其中一个。我已经更新了上面的内容以重命名内部的。
    猜你喜欢
    • 2015-07-02
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 1970-01-01
    • 2017-10-23
    相关资源
    最近更新 更多