我正在使用Meteor和Twitter API进行项目。我想从Twitter获取有关用户的信息。我编写了一个函数,例如只返回Twitter用户的位置。我相信这是在Meteor上提出请求的正确方法。这是:
Meteor.methods({getTwitterLocation: function (username) {
Meteor.http.get("https://api.twitter.com/1/users/show.json?screen_name="+ username +"&include_entities=true", function(error, result) {
if (result.statusCode === 200) {
var respJson = JSON.parse(result.content);
console.log(respJson.location);
console.log("location works");
return (respJson.location)
}else {
return ( "Unknown user ")
}
});
}});
现在这个函数会在我的Git Bash上记录控制台中的内容。我通过Meteor.call得到某人的位置。但我想发布该函数在页面上返回的内容。在我的情况下,我想发布用户的个人资料。这不起作用。但是console.log(respJson.location)返回我的Git Bash中的位置,但它不会在配置文件页面上显示任何内容。这就是我在个人资料页面上所做的:
profile.js:
Template.profile.getLocation= function(){
return Meteor.call("getTwitterLocation","BillGates");
}
profile.html:
<template name="profile">
from {{getLocation}}
</template>
有了这个,我在我的Git Bash上获得了“西雅图,华盛顿”和“位置”,但在个人资料页面上没有任何内容。如果有人知道我能做什么,那真的很感激。谢谢。
答案 0 :(得分:3)
首先,当从服务器返回数据时,您需要使用synchronous call,因为当服务器已经认为流星方法已经完成时,回调将返回数据。 (回调将在以后触发,当从服务器返回数据时,流星客户端本来会得到响应)
var result = Meteor.http.get("https://api.twitter.com/1/users/show.json?screen_name="+ username +"&include_entities=true");
if (result.statusCode === 200) {
var respJson = JSON.parse(result.content);
console.log(respJson.location);
console.log("location works");
return (respJson.location)
}else {
return ( "Unknown user ")
}
第二个是您需要使用Session哈希来从模板返回数据。这是因为获取响应需要时间,而getLocation会期望得到即时结果(没有回调)。目前,客户端javascript无法使用服务器上的同步api调用。
Template.profile.getLocation= function(){
return Session.get("twitterlocation");
}
使用模板created event发起流星呼叫:
Template.profile.created = function() {
Meteor.call("getTwitterLocation","BillGates", function(err,result) {
if(result && !err) {
Session.set("twitterlocation", result);
}
else
{
Session.set("twitterlocation", "Error");
}
});
});
<强>更新强>
Twitter已将其API更新为1.1,因此需要进行一些修改:
现在需要使用1.1而不是1来交换到1.1 api。此外,您需要OAuth您的请求。见https://dev.twitter.com/docs/auth/authorizing-request。下面包含示例数据,但您需要获得正确的密钥
var authkey = "OAuth oauth_consumer_key="xvz1evFS4wEEPTGEFPHBog",
oauth_nonce="kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg",
oauth_signature="tnnArxj06cWHq44gCs1OSKk%2FjLY%3D",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp=""+(new Date().getTime()/1000).toFixed(0)+"",
oauth_token="370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb",
oauth_version="1.0"";
请务必删除换行符,我已将其换行以便于阅读。
var result = Meteor.http.get("https://api.twitter.com/1.1/users/show.json?screen_name="+ username +"&include_entities=true",{headers:{Authorization : authkey});
如果您觉得这有点麻烦,可能更容易通过https://github.com/Sewdn/meteor-twitter-api使用meteorite这样的包来OAuth您的请求。