2

我正在尝试使用passportjs在nodejs中执行twitter oauth但出现错误

Cannot GET /auth/twitter/callback?oauth_token=alksdkalsjdsjd23232378skjdfjsdhf&oauth_verifier=234jjh23j4k234k23h4j2h342k34hj

这是我的节点 js 代码

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


passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(obj, done) {
  done(null, obj);
});


passport.use(new TwitterStrategy({
    consumerKey: 'xxxxxxxxxxxxxxxxxxxx',
    consumerSecret: 'xxxxxxxxxxxxxxxxxxxxxxxxxx',
    callbackURL: 'http://127.0.0.1:3000/auth/twitter/callback'
},
 function(token, tokenSecret, profile, done) {
     process.nextTick(function () {
      return done(null, profile);
    });
 }
 ));


var app = express();

// configure Express
app.configure(function() {
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.logger());
  app.use(express.cookieParser());
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.session({ secret: 'keyboard cat' }));
  // Initialize Passport!  Also use passport.session() middleware, to support
  // persistent login sessions (recommended).
  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('/login', function(req, res){
  res.sendfile('./views/auth.html');
});




app.get('/auth/twitter', passport.authenticate('twitter'));

app.get('auth/twitter/callback',
  passport.authenticate('twitter', { successRedirect: '/success',
                     failureRedirect: '/login' }));

app.get('/success', function(req, res){
    res.send("success logged in");
});

app.listen(process.env.PORT || 3000);
4

2 回答 2

2

编辑路线定义/中 缺少。auth/twitter/callback

同样对于路由器/auth/twitterauth/twitter/callbackpassport.authenticate()因为中间件会做认证,你应该有路由处理功能。

所以你的路线的定义应该是这样的:

app.get('/auth/twitter', 
         passport.authenticate('twitter'),
         function(req, res) {}); // empty route handler function, it won't be triggered
app.get('/auth/twitter/callback', 
         passport.authenticate('twitter', { 
                                successRedirect: '/success',
                                failureRedirect: '/login' }),
         function(req, res) {}); // route handler
于 2013-10-15T20:34:12.873 回答
0

您不需要空路由处理程序function(req, res) {}- 您可以将参数排除在外,express 会理解您不打算使用该处理程序

于 2016-09-22T16:49:52.673 回答