使用Passport.js和Express.js的HTTP GET请求

时间:2012-12-02 16:27:56

标签: node.js twitter oauth express passport-twitter

我是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' });
};

3 个答案:

答案 0 :(得分:2)

安装模块:     $ 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

答案 1 :(得分: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');
        });
     }

答案 2 :(得分:-1)

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

https://npmjs.org/package/request