2017-05-30 48 views
-1

我很新node.jspassport.js。我試圖學習如何使用this video製作驗證應用程序,但在視頻中達到31:04後,我一直收到此錯誤。用戶認證使用passport.js給出錯誤

"TypeError: Cannot read property 'name' of undefined at Authenticator.use"

這是我app.js文件:

var express = require('express'); 
var bodyParser = require('body-parser'); 
var cookieParser = require('cookie-parser'); 
var expressSession = require('express-session'); 

var passport = require('passport'); 
var passportLocal = require('passport-local'); 

var app = express(); 

app.set('view engine', 'ejs'); 

app.use(bodyParser.urlencoded({ extended: false })); 
app.use(cookieParser()); 
    secret: process.env.SESSION_SECRET 
app.use(expressSession({ || 'secret', 
    resave: false, 
    saveUninitialized: false 
})); 


app.use(passport.initialize()); 
app.use(passport.session()); 

passport.use(passportLocal.Strategy(function(username, password, done){ 
    //connect to a real db here 
    if(username===password){ 
     done(null,{id: username, name: username}); 
     //these actually have to bbe pulled from the db 
    } 
    else{ 
     done(null,null); 
    } 
})); 


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

    }); 
}); 

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

app.post('/login', passport.authenticate('local' , function(req,res){ 
    res.redirect('/'); 
})); 



var port = process.env.PORT || 1337; 

app.listen(port, function(err,res){ 
    if(err) 
     console.log(err); 
    else 
     console.log('server started on localhost:'+ port +' /'); 
}); 

回答

0

你必須調用new操作:

passport.use(new passportLocal.Strategy(function(username, password, done){ 
    //connect to a real db here 
    if(username===password){ 
     done(null,{id: username, name: username}); 
     //these actually have to bbe pulled from the db 
    } 
    else{ 
     done(null,null); 
    } 
})); 

我相信這是你的問題。

+0

是的,就是這樣!非常感謝。^_ ^ –