1

我正在尝试为我的网站制作“与 Twitter 连接”功能,这是我第一次使用 Passport.js。

一段时间以来我遇到了一个问题:尝试api时,/twitter/callback页面的passport.authenticate函数卡住了,我无法解决这个问题

我在我的本地主机系统上运行我的应用程序。这是我的 index.js 页面代码。home.ejs 只包含一个 EJS 模板,我在其中显示用户名。

var express = require('express');
var app = express();

const cookieParser = require('cookie-parser');
app.use(cookieParser('thissecretrocks'));

const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

const session = require('express-session');
app.use(session({
    resave: true,
    saveUninitialized: true,
    secret: 'bla bla bla' 
}));

const mongoose = require('mongoose');
mongoose.connect('mongodb+srv://Something', {useNewUrlParser: true, useUnifiedTopology: true});
const db = {};
db.users = require('./db/users');

const passport = require('passport');
app.use(passport.initialize());
app.use(passport.session());

const Twitter = require('passport-twitter');
var Strategy = require('strategy');
const TwitterStrategy = Twitter.Strategy;

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

passport.deserializeUser(function (id, done) {
    db.users.findById(id, function (err, user) {
        done(err, user);
    });
});

passport.use(new TwitterStrategy({
    consumerKey: '5KSomethingMx',
    consumerSecret: 'tld1Something6M2q',
    callbackURL: "http://127.0.0.1:3000/auth/twitter/callback",
},
function(token, tokenSecret, profile, cb) {
    console.log(profile);
    /*const newUser = new db.users({
        twitter: profile.id
    });
    newUser.save();*/
}
));

app.use('/cdn', express.static('cdn'));

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

app.get('/fail', function(req, res) {
    console.log('FAIL');
    res.render('home.ejs', {username: 'req.user.username'});
});

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

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

app.listen(3000);
4

0 回答 0