简体   繁体   English

使用Node应用程序调用外部API(KeystoneJS)

[英]Calling an external API with a Node application (KeystoneJS)

I'm newer to Node and trying to learn how to modify my Keystone.JS app so it can call data from an API (JSON or XML) and display it in the view that is rendered. 我是Node的新手,试图学习如何修改Keystone.JS应用程序,以便它可以从API(JSON或XML)中调用数据并将其显示在呈现的视图中。

The current code in my app is essentially a cloned version of this demo app https://github.com/JedWatson/keystone-demo except the view engine is Handlebars in my app. 我的应用程序中的当前代码实质上是该演示应用程序的克隆版本https://github.com/JedWatson/keystone-demo,除了视图引擎是我的应用程序中的Handlebars。 What I have tried to so far is is installing the request package and played around with code from the documentation in a my keystone.js file with no luck. 到目前为止,我一直试图安装请求包,并在我的keystone.js文件中使用文档中的代码进行测试,但是没有运气。

Then I created a model/api.js file, routes/api.js, routes/views/api.js and templates/views/api.hbs and again played with code examples in the request documentation but failed to even grasp what I was doing and how all of these new pages even worked within my app. 然后,我创建了一个model / api.js文件,routes / api.js,routes / views / api.js和templates / views / api.hbs,并再次在请求文档中使用了代码示例,但是甚至无法理解我的意思。以及所有这些新页面如何在我的应用程序中运行。

I would greatly appreciate figuring out how to call an API and display the requested info in one of the apps rendered views. 我将不胜感激弄清楚如何调用API并在呈现的应用程序视图之一中显示请求的信息。 Thank you in advance! 先感谢您!

You could hit the api from your model logic like so https://github.com/r3dm/shpe-sfba/blob/master/models/Event.js#L69 You could use node's built in http library http://devdocs.io/node/http 您可以从模型逻辑中访问api,例如https://github.com/r3dm/shpe-sfba/blob/master/models/Event.js#L69。您可以使用node内置的http库http:// devdocs。 IO /节点/ 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);
    });
});

If you want the data to be fetched in some other scenario try adding the http request to initLocals in routes/middleware.js . 如果您希望在其他情况下获取数据,请尝试将http请求添加到routes/middleware.js initLocals中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM