1

我是 Express.js、Node.js 和 Passport.js 的新手。我正在尝试开发一个应用程序,用户使用他们的 Twitter 帐户登录,然后他们可以看到他们的提及(其他 Twitter 用户提到登录用户的 Twitter 用户名的推文)。我遇到了 Passport.js,我已经能够成功地使用它,允许用户使用他们的 Twitter 帐户登录。

但是,我不确定如何格式化 Twitter 提及的服务器端 HTTP GET 请求。我已经在https://dev.twitter.com/docs/api/1/get/statuses/mentions多次查看 Twitter API ,但由于我不熟悉 Node/Express/Passport 平台,所以我不确定如何在服务器端执行此请求以返回 JSON 格式的提及。该应用程序设置为只读,因为它只需要能够查看与关联用户相关的推文。

前端基于 EJS。以下是我拥有的可能相关的代码。非常感谢您的帮助。

-joshingmachine

/app.js

/**
 * Module dependencies.
 */

var express = require('express')
  , passport = require('passport')
  , http = require('http')
  , util = require('util')
  , path = require('path')
  , TwitterStrategy = require('passport-twitter').Strategy;

var TWITTER_CONSUMER_KEY = "theConsumerKeyForMyApp";
var TWITTER_CONSUMER_SECRET = "theConsumerSecretForMyApp";

var users = [];

// Passport session setup.
passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  var user = users[id];
  done(null, user);
});


// Use the TwitterStrategy within Passport.
passport.use(new TwitterStrategy({
    consumerKey: TWITTER_CONSUMER_KEY,
    consumerSecret: TWITTER_CONSUMER_SECRET,
    callbackURL: "http://127.0.0.1:3000/auth/twitter/callback"
  },
  function(token, tokenSecret, profile, done) {
    //console.log(token);
    //console.log(tokenSecret);
    //console.log(profile);
    // asynchronous verification, for effect...
    process.nextTick(function () {
      var user = users[profile.id] || (users[profile.id] = profile);
      done(null, user);
    });
  }
));

var app = express();

// configure Express
app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser());
  app.use(express.session({ secret:'secret'}));
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});


app.get('/', function(req, res){
  res.render('index', { user: req.user });
});

app.get('/account', ensureAuthenticated, function(req, res){
  res.render('account', { user: req.user });
});

app.get('/login', function(req, res){
  res.render('login', { user: req.user });
});

// GET /auth/twitter
app.get('/auth/twitter',
  passport.authenticate('twitter'),
  function(req, res){
    // The request will be redirected to Twitter for authentication, so this
    // function will not be called.
  });

// GET /auth/twitter/callback
app.get('/auth/twitter/callback', 
  passport.authenticate('twitter', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/');
});

// Create server
http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

// Simple route middleware to ensure user is authenticated.
function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) { return next(); }
  res.redirect('/login');
}

app.use(function(req, res, next){
  res.send(404, '404 Not Found');
});

/routes/index.js

/*
 * GET home page.
 */

exports.index = function(req, res){
  res.render('index', { title: 'Express' });
};
4

3 回答 3

3

安装模块:

npm install oauth

然后使用此代码创建您的 GET 请求(根据需要替换变量)。

var oauth = new OAuth.OAuth(
  'https://api.twitter.com/oauth/request_token',
  'https://api.twitter.com/oauth/access_token',
  'your application consumer key',
  'your application secret',
  '1.0A',
  null,
  'HMAC-SHA1'
);
oauth.get(
  'https://api.twitter.com/1.1/trends/place.json?id=23424977',
  'your user toke for this app', //test user token
  'your user secret for this app', //test user secret            
  function (e, data, res){
    if (e) console.error(e);        
    console.log(require('util').inspect(data));
    done();      
  });    

如果您需要更多信息,请在此处参考。祝你好运! https://github.com/ciaranj/node-oauth

于 2013-06-29T18:58:40.257 回答
0

我创建了类似于您正在尝试做的事情。由于您已成功登录,我假设您能够获取访问令牌和密码。一旦你有了这些,就可以使用像mtwitter这样的外部库。我这样打了电话(编辑了我从数据库中获取令牌的部分):

app.get('/twitter/userMentions', function (req, res) {
    var twit = new mtwitter({
        consumer_key: consumerKey,
        consumer_secret: consumerSecret,
        access_token_key: token,
        access_token_secret: secret
    });

    twit.get("/statuses/mentions_timeline", { "include_entities": false },
        function (err, data) {
            if (err) {
                res.write(err.toString());
            }
            else res.write(JSON.stringify(data));

            res.end('\n');
        });
     }
于 2013-07-19T22:37:58.727 回答
-1

我认为您正在寻找请求节点模块!

https://npmjs.org/package/request

于 2013-02-08T10:28:40.600 回答