【问题标题】:Calling an external API with a Node application (KeystoneJS)使用 Node 应用程序调用外部 API (KeystoneJS)
【发布时间】:2015-01-12 02:22:46
【问题描述】:

我是 Node 的新手,正在尝试学习如何修改我的 Keystone.JS 应用程序,以便它可以从 API(JSON 或 XML)调用数据并将其显示在呈现的视图中。

我的应用程序中的当前代码本质上是这个演示应用程序https://github.com/JedWatson/keystone-demo 的克隆版本,除了视图引擎是我的应用程序中的 Handlebars。到目前为止,我尝试的是安装请求包并在我的 keystone.js 文件中使用文档中的代码,但没有运气。

然后我创建了一个 model/api.js 文件、routes/api.js、routes/views/api.js 和 templates/views/api.hbs 并再次使用请求文档中的代码示例,但未能掌握我在做什么以及所有这些新页面是如何在我的应用程序中运行的。

如果能弄清楚如何调用 API 并在其中一个应用程序呈现的视图中显示请求的信息,我将不胜感激。提前谢谢!

【问题讨论】:

    标签: javascript json node.js xmlhttprequest keystonejs


    【解决方案1】:

    你可以像这样https://github.com/r3dm/shpe-sfba/blob/master/models/Event.js#L69从你的模型逻辑中点击api你可以使用node的内置http库http://devdocs.io/node/http

    // Below we call the Facebook api to fill in data for our model
    Event.schema.pre('save', function(next) {
        var myEvent = this;
    
        var apiCall = 'your API string';
    
        https.get(apiCall, function(res) {
            var body = '';
            res.on('data', function(d) { body += d; });
            res.on('end', function() {
            body = JSON.parse(body);
    
            if (body.error) {
                var err = new Error('There was an error saving your changes. Make sure the Facebook Event is set to "Public" and try again');
                next(err);
            } else {
                next();
            });
        })
        .on('error', function(e) {
            console.log(e);
        });
    });
    

    如果您希望在其他情况下获取数据,请尝试将 http 请求添加到 routes/middleware.js 中的 initLocals

    【讨论】:

    • 谢谢哈利,今晚我会试试这个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 2013-08-17
    • 2011-09-05
    • 2013-11-18
    相关资源
    最近更新 更多