Node.js module.exports passport已验证为路由
我想在一个文件中分隔每组路由。我需要在大多数路由中使用isAuthenticated来限制访问。当我把所有路由放在同一个文件中时,它就工作了 当我在auth.js和order.js中使用Node.js module.exports passport已验证为路由,node.js,express,authentication,routes,passport-local,Node.js,Express,Authentication,Routes,Passport Local,我想在一个文件中分隔每组路由。我需要在大多数路由中使用isAuthenticated来限制访问。当我把所有路由放在同一个文件中时,它就工作了 当我在auth.js和order.js中使用module.exports=isAuthenticated时,我使用var auth=require('auth.js')当我转到auth.js中定义的路由时,我将得到一个错误“isAuthenticated is not defined”(isAuthenticated is not defined) 我正在
module.exports=isAuthenticated
时,我使用var auth=require('auth.js')代码>当我转到auth.js中定义的路由时,我将得到一个错误“isAuthenticated is not defined”(isAuthenticated is not defined)
我正在使用Express.js中间件“Passport本地策略”(遵循tutsplus提供的教程,并从中下载github存储库)
我的项目结构:
bin/www
models/auth/init.js
models/auth/user.js
models/auth/signup.js
models/auth/login.js
models/order.js
views/error.pug
views/index.pug
views/home.pug
views/layout.pug
views/order.pug
views/register.pug
routes/order.js
routes/auth.js
public/stylesheets/style.css
app.js
db.js
./routes/auth.js:
var express = require('express');
var router = express.Router();
var isAuthenticated = function (req, res, next) {
// if user is authenticated in the session, call the next() to call the next request handler
// Passport adds this method to request object. A middleware is allowed to add properties to
// request and response objects
if (req.isAuthenticated())
return next();
// if the user is not authenticated then redirect him to the login page
res.redirect('/');
}
module.exports = isAuthenticated;
module.exports = function(passport){
/* GET login page. */
router.get('/', function(req, res) {
// Display the Login page with any flash message, if any
res.render('index', { message: req.flash('message') });
});
/* Handle Login POST */
router.post('/login', passport.authenticate('login', {
successRedirect: '/home',
failureRedirect: '/',
failureFlash : true
}));
/* GET Registration Page */
router.get('/signup', function(req, res){
res.render('register',{message: req.flash('message')});
});
/* Handle Registration POST */
router.post('/signup', passport.authenticate('signup', {
successRedirect: '/home',
failureRedirect: '/signup',
failureFlash : true
}));
/* GET Home Page */
router.get('/home', isAuthenticated, function(req, res){
res.render('home', { user: req.user });
});
/* Handle Logout */
router.get('/signout', function(req, res) {
req.logout();
res.redirect('/');
});
return router;
}
./routes/order.js:
var express = require('express');
var router = express.Router();
var order = require('../models/order');
var auth = require('./auth.js');
module.exports = function(passport){
router.get('/order', isAuthenticated, function(req, res){
res.render('order');
});
router.post('/order', isAuthenticated, function(req, res)
{
var testorder = new order({
orderid: '52363',
productname: 'it works',
quantity: 1337
});
testorder.save(function (err) {
if (err) {console.log(err.stack);}
console.log('saving done...');
});
res.render('order', { product: req.body.productname });
});
};
//app.js
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var pug = require('pug');
var dbConfig = require('./db');
var mongoose = require('mongoose');
// Connect to DB
mongoose.connect(dbConfig.url);
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
// TODO - Why Do we need this key ?
app.use(expressSession({secret: 'mySecretKey'}));
app.use(passport.initialize());
app.use(passport.session());
// Using the flash middleware provided by connect-flash to store messages in session
// and displaying in templates
var flash = require('connect-flash');
app.use(flash());
// Initialize Passport
var initPassport = require('./models/auth/init.js');
initPassport(passport);
var auth = require('./routes/auth')(passport);
var order = require('./routes/order');
app.use('/', auth);
app.use('/order', order);
/// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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
});
});
}
module.exports = app;
请尝试使用auth.IsAnutheticated(),
它应该是这样工作的。我在router.get('/order',auth.isAuthenticated,function(req,res){….}中更改了它。在order.js中我得到了这个堆栈跟踪:Try auth.isAuthenticated()错误:auth.isAuthenticated不是一个函数您的代码似乎结构不好,请尝试正确地构造它。同时,为了快速解决您的问题,请复制isAuthenticated函数并将其粘贴到需要中间件的任何位置。然后这应该可以工作router.post('/order',isAuthenticated,function(req,res){…})