如何使用Meteor发起API调用

44

好的,这是Twitter API:

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

有没有人能够给我一些提示,如何使用Meteor调用这个API或链接?

更新:

这是我尝试过的代码,但它没有显示任何响应。

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 () {
    });
}

我快速查看了文档,认为查看http://docs.meteor.com/#meteor_http_get会很有用,尽管我以前没有使用过Meteor,所以对语法不是太确定,但我现在会为您查看... - Opentuned
HTTP.get() 的文档现在位于 http://docs.meteor.com/#/full/http_get。 - Jon Onstott
5个回答

56

您正在在客户端作用域块中定义您的 checkTwitter Meteor.method。由于客户端无法跨域调用(除非使用jsonp),因此您需要将此块放入一个 Meteor.isServer 块中。

另外,根据文档,您的 checkTwitter 函数的客户端 Meteor.method 只是服务器端方法的存根。您需要查看文档以获取有关服务器端和客户端 Meteor.methods 如何协同工作的完整解释。

这里是一个可行的http调用示例:

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
    });
}

实际上它返回的是XML而不是JSON,因此在尝试执行警报时它显示未定义。 - iJade
http://search.twitter.com/search.json?q=perkytweets -- 这个工作了吗? - TimDog
我刚刚运行了代码,看起来很好。results.content应该给你一个字符串。不过我正在编辑我的答案,因为选项1行不通——除非利用jsonp,否则无法在客户端进行跨域ajax。但我不想让事情变得复杂。 - TimDog
没有这个包就会默默失败,所以需要使用 meteor add http - Cees Timmerman
你好,你在哪里使用API密钥?它能否在没有API密钥的情况下运行? - Rahul Khatri
显示剩余2条评论

29

这可能看起来很基础,但HTTP包不会默认安装在你的Meteor项目中,需要按需安装。

在命令行中执行以下操作之一:

  1. 只使用Meteor:
    meteor add http

  2. Meteorite:
    mrt add http

Meteor HTTP文档


6

在客户端,Meteor.http.get 是异步的,所以您需要提供一个回调函数:

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

4
使用Meteor.http.get。根据文档
Meteor.http.get(url, [options], [asyncCallback]) Anywhere
Send an HTTP GET request. Equivalent to Meteor.http.call("GET", ...).

实际上,文档中包含了一些使用Twitter的示例,因此您应该能够从中开始入手。


谢谢您的回复。我刚刚更新了我的代码,但它仍然无法正常工作。没有输出显示。 - iJade

0

如果在服务器端提供http.get的回调函数,那么它将是异步调用,因此我的解决方案是对客户端上未定义返回值的处理方式是:

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

由于我没有传递回调函数给HTTP.get,所以它一直等到我收到响应为止。希望这有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接