Meteor检索Twitter凭据

时间:2015-02-21 09:35:26

标签: meteor

我目前有一个带有自定义登录(电子邮件/密码)的Meteor应用程序。我打算要求用户链接他们的Twitter帐户(如果可用的话,每个用户有多个Twitter帐户),以便我可以代表他们发送API请求(获取推文,发布推文,搜索推文等)。

我相信这样做,我需要用户的oauth_token和oauth_secret。

我正在使用Tim Haines' '叽叽喳喳'包试图实现这一点。我也在使用以下资源: Twitter.requestCredential function response https://github.com/timhaines/test-accounts/blob/master/test-accounts.js

我能够启动登录对话框,输入Twitter用户名/密码,并获得一个令牌字符串,这与每次登录尝试都不同。所以我知道Twitter.requestCredential()正在发挥作用。但是,当我将令牌传递给代码Twitter.retrieveCredential(token)中的行时,它不返回任何内容(未定义)。

这是我的客户端代码(直接来自上面的链接):

            Twitter.requestCredential(function(tokenOrError) {
            if(tokenOrError && tokenOrError instanceof Error) {
                console.log('Error:' + tokenOrError);
            } else {
                Meteor.call('retrieveTwitterCredential', tokenOrError, function(error, result) {
                    if(error)
                        console.log(error.reason);
                    else {
                        console.log('DEMO ONLY - DON\'T send unfiltered credentials to the client on a production app');
                        console.log('Result:', result);
                    }
                });
            }
        });

这是我的服务器端代码(直接来自上面的链接):

        console.log(token);
    credential = Twitter.retrieveCredential(token);
    console.log(credential);
        if(credential instanceof Error)
            throw new Meteor.Error(500, credential.message);
        else
            return credential;

'凭证'似乎未定义。在过去的两周里,我一直在梳理头发,所以如果有人能提供帮助,那将非常感激。

提前致谢!

1 个答案:

答案 0 :(得分:0)

我找到了解决方案,所以我想发布它以防万一其他人遇到同样的问题。

当您使用Meteor方法调用INSIDE异步函数时,您需要使用Meteor.bindEnvironment()来包装回调并使用Meteor方法中的函数结果。

以下是适合我的解决方案:

Twitter.get('statuses', id, Meteor.bindEnvironment(function(error, response) {
                    // handle the error
                } else {
                    //do stuff with the response
                } 
}, function() { console.log('Failed to bind environment'); }));

P.S。这不仅适用于Twitter身份验证,还适用于任何异步功能。我不得不使用Meteor.bindEnvironment()来存储异步函数的结果,我需要通过进行Meteor方法调用来写入数据库。它也适用于此。

希望这可以帮助有需要的人!