How to make an API call using meteor

守給你的承諾、 提交于 2019-12-28 07:40:22

问题


Ok here is the twitter API,

http://search.twitter.com/search.atom?q=perkytweets

Can any one give me any hint about how to go about calling this API or link using Meteor

Update::

Here is the code that i tried but its not showing any response

if (Meteor.isClient) {
    Template.hello.greeting = function () {
        return "Welcome to HelloWorld";
    };

    Template.hello.events({
        'click input' : function () {
            checkTwitter();
        }
    });

    Meteor.methods({checkTwitter: function () {
        this.unblock();
        var result = Meteor.http.call("GET", "http://search.twitter.com/search.atom?q=perkytweets");
        alert(result.statusCode);
    }});
}

if (Meteor.isServer) {
    Meteor.startup(function () {
    });
}

回答1:


You are defining your checkTwitter Meteor.method inside a client-scoped block. Because you cannot call cross domain from the client (unless using jsonp), you have to put this block in a Meteor.isServer block.

As an aside, per the documentation, the client side Meteor.method of your checkTwitter function is merely a stub of a server-side method. You'll want to check out the docs for a full explanation of how server-side and client-side Meteor.methods work together.

Here is a working example of the http call:

if (Meteor.isServer) {
    Meteor.methods({
        checkTwitter: function () {
            this.unblock();
            return Meteor.http.call("GET", "http://search.twitter.com/search.json?q=perkytweets");
        }
    });
}

//invoke the server method
if (Meteor.isClient) {
    Meteor.call("checkTwitter", function(error, results) {
        console.log(results.content); //results.data should be a JSON object
    });
}



回答2:


This might seem rudimentary - but the HTTP package does not come by default in your Meteor project and requires that you install it a la carte.

On the command line either:

  1. Just Meteor:
    meteor add http

  2. Meteorite:
    mrt add http

Meteor HTTP Docs




回答3:


Meteor.http.get on the client is async, so you will need to provide a callback function :

Meteor.http.call("GET",url,function(error,result){
     console.log(result.statusCode);
});



回答4:


Use Meteor.http.get. Per the docs:

Meteor.http.get(url, [options], [asyncCallback]) Anywhere
Send an HTTP GET request. Equivalent to Meteor.http.call("GET", ...).

The docs actually include some examples of using Twitter, so you should be able to get started with them.




回答5:


on server side if you provide the call back to http.get it will be asynch call so my solutions to that undefined return on client was

var result = HTTP.get(iurl); return result.data.response;

as i did not pass a call back to HTTP.get so it waited until i got response. hope it helps



来源:https://stackoverflow.com/questions/14320610/how-to-make-an-api-call-using-meteor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!