gpt4 book ai didi

javascript - 如何使用 express router 正确调用 passport.js 函数?

转载 作者:行者123 更新时间:2023-11-30 12:24:21 25 4
gpt4 key购买 nike

我正在尝试调用 passport.authenticate 函数作为对我的注册 View 的发布请求的响应。我一直在关注this tutorial here让我了解 passport.js 和 express,但是已经完成了第一页的说明并对 express.js 4.0 进行了必要的更改,我尝试访问的每一页都返回错误 500 并显示以下堆栈跟踪:

TypeError: Object #<serverResponse> has no method 'authenticate'
at module.exports (/home/myUserName/Desktop/manufacturing/routes/index.js:66:37)
at Layer.handle [as handle_request] (/home/myUserName/Desktop/manufacturing/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/home/myUserName/Desktop/manufacturing/node_modules/express/lib/router/index.js:302:13)
at /home/myUserName/Desktop/manufacturing/node_modules/express/lib/router/index.js:270:7
at Function.proto.process_params (/home/myUserName/Desktop/manufacturing/node_modules/express/lib/router/index.js:321:12)
at next (/home/myUserName/Desktop/manufacturing/node_modules/express/lib/router/index.js:261:10)
at /home/myUserName/Desktop/manufacturing/node_modules/connect-flash/lib/flash.js:21:5
at Layer.handle [as handle_request] (/home/myUserName/Desktop/manufacturing/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/home/myUserName/Desktop/manufacturing/node_modules/express/lib/router/index.js:302:13)
at /home/myUserName/Desktop/manufacturing/node_modules/express/lib/router/index.js:270:7

这是/routes/index.js 的代码:

var express = require('express');
var bodyParser = require('body-parser');
var router = express.Router();

module.exports = function(app, passport) {
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', {
title: 'Home Page'
});
});

/* GET about page */
router.get('/about', function(req, res, next) {
res.render('about', {
title: 'About Us'
});
});

/* GET contact page */
router.get('/contact', function(req, res, next) {
res.render('contact', {
title: 'Contact Us'
});
});

/* GET login page */
router.get('/login', function(req, res, next) {
res.render('login', {
title: 'User Login',
message: req.flash('loginMessage')
});
});

/* GET register page */
router.get('/register', function(req, res, next) {
res.render('register', {
title: 'User Registration',
message: req.flash('signupMessage')
});
});

/* POST register page */
router.post('/register', passport.authenticate('local', {
successRedirect : '/',
failureRedirect : '/register',
failureFlash : true
}));

/* Log Out */

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

/* 404 - page not found */
router.get('*', function(req, res){
res.render('404', {
title: '404 - Not Found'
});
});

// Route middleware to make sure a user is logged in
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/');
};
};

这是我的 server.js:

var express       = require('express');
var path = require('path');
var logger = require('morgan');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var flash = require('connect-flash');

// Database

var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
require('./config/passport')(passport);

// Routes
var routes = require('./routes/index');

var port = process.env.PORT || 3000;
var app = express();

// Express configuration
app.use(logger('dev')); // log every request to console
app.use(bodyParser.json()); // get information from html forms
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser()); // read cookies (needed for auth)
app.use(express.static(path.join(__dirname, 'public')));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
if (app.get('env') === 'development') {
app.locals.pretty = true;
}

// Passport configuration

app.use(session({ secret: 'MySecretHere',
saveUninitialized: true,
resave: true})); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

app.use('/', routes);

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});

app.listen(port);
console.log('Server running on ' + port);

最佳答案

您收到错误的原因是因为您导出的函数将 apppassport 作为您的 http 处理程序的参数,但是当您需要它时server.js 您没有传递 passportapp

您需要以某种方式将 passport 传递到 require 中。您可以将路线文件更改为如果您使用的是 express.Router

   var router = express.Router();
module.exports = function(passport) {
// init your routes with passport and router
router.post('/' function(req, res) {
//...
});
// make sure to return router in the function though
return router;
}

如果不使用 express.Router,您可以传递 apppassport 并简单地将处理程序附加到 app

   module.exports = function (app, passport) {
app.post('/', function(req, res) {
//...
});
// no need to return app
}

然后在 server.js 中

     // if your using `express.Router()` in routes file
app.use('/', require('./routes')(passport));
// If your registering handler on app itself just bootstrap it
require('./routes')(app, passport);

关于javascript - 如何使用 express router 正确调用 passport.js 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29988569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com