TypeError:无法读取Express框架的未定义属性“ apply”

kyl*_*las -1 javascript node.js express

app.js

var app = express();
app.listen(PORT, () => console.log(`Listening on ${ PORT }`));


// all environments
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
  secret: 'keyboard cat',
  resave: true,
  saveUninitialized: false,
  // cookie: { 
  //   maxAge: 365 * 24 * 60 * 60 * 1000,
  //   path : '/'
  // }
}));

app.use('/portal/admin', adminRouter);
app.use('/portal/merchant', indexRouter);
app.use('/users', usersRouter);
app.use('/api/v1/users',apiRouter);
app.use('/api/v1/users',customerInstallmentAPIRouter);
app.use('/api/v1/payment',paymentMethodAPIRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  // Request methods you wish to allow
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, content-type, Authorization, Content-Type');
  res.setHeader('Access-Control-Allow-Credentials', true);
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

app.get('/portal/merchant',indexRouter); //call to index site

//login
app.get('/login', usersRouter); // call to login site
app.post('/login',usersRouter); // post to /users/login site

//logout
app.get('/home/logout',usersRouter);

//signup
app.get('/signup', usersRouter); // call to /users/signup site
app.post('/signup',usersRouter); //call to /post/signup 

//dashboard
app.get('/home/dashboard',usersRouter);

//profile
app.get('/home/profile',usersRouter);

db.sequelize
.authenticate()
.then(() => {
  console.log('Connection has been established successfully.');
})
.catch(err => {
  console.error('Unable to connect to the database:', err);
});

//run scheduler to check due date
//cronJob.dueDateCronJob();

app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions

require('./routes/adminportal/home.js')(app,passport); 

module.exports = app;
Run Code Online (Sandbox Code Playgroud)

似乎错误发生在 require('./routes/adminportal/home.js')(app,passport);

护照

// config/passport.js

// load all the things we need
var LocalStrategy   = require('passport-local').Strategy;

// load up the user model
var User            = require('../models/admin.js');

// expose this function to our app using module.exports
module.exports = function(passport) {

    // =========================================================================
    // passport session setup ==================================================
    // =========================================================================
    // required for persistent login sessions
    // passport needs ability to serialize and unserialize users out of session

    // used to serialize the user for the session
    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    // used to deserialize the user
    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });
    // =========================================================================
    // LOCAL LOGIN =============================================================
    // =========================================================================
    // we are using named strategies since we have one for login and one for signup
    // by default, if there was no name, it would just be called 'local'

    passport.use('local-login', new LocalStrategy({
        // by default, local strategy uses username and password, we will override with email
        usernameField : 'email_address',
        passwordField : 'password',
        passReqToCallback : true // allows us to pass back the entire request to the callback
    },
    function(req, email, password, done) { // callback with email and password from our form

        // find a user whose email is the same as the forms email
        // we are checking to see if the user trying to login already exists
        User.findOne({ 'local.email' :  email }, function(err, user) {
            // if there are any errors, return the error before anything else
            if (err)
                return done(err);

            // if no user is found, return the message
            if (!user)
                return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash

            // if the user is found but the password is wrong
            if (!user.validPassword(password))
                return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata

            // all is well, return successful user
            return done(null, user);
        });

    }));
};
Run Code Online (Sandbox Code Playgroud)

home.js

var express = require('express');
var router = express.Router();
var db = require('../sequelizeDB.js');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;

/* GET home page. */
router.get('/', function(req, res, next) {
  if(req.session.userId != null){
    message = '';
    //res.render('dashboard',{message:message});
    res.redirect("adminportal/home.ejs");
  }else{
    var message = '';
    var sess = req.session; 
    res.render('adminportal/login.ejs',{message: message});   
  }
});



router.post('/login',passport.authenticate('local-login', {
  successRedirect : '/listOfCustomers', // redirect to the secure profile section
  failureRedirect : '/', // redirect back to the signup page if there is an error
  failureFlash : true // allow flash messages
}), function(req, res, next) {
  var message = '';
  var sess = req.session; 

 if(req.method === "POST"){
    var post  = req.body;
    var name= post.user_name;
    var pass= post.password;

  } else {
      res.render('adminportal/login.ejs',{message: message});
  }         
});

function isLoggedIn(req, res, next) {

  // if user is authenticated in the session, carry on 
  if (req.isAuthenticated())
      return next();

  // if they aren't redirect them to the home page
  res.redirect('adminportal/login.ejs');
}


router.get('/listOfCustomers',isLoggedIn, function(req, res, next) {

  if(req.method === "GET"){
      db.customers.findAll().then(customers =>{
        res.render('adminportal/listOfCustomers.ejs',{data:customers});
      })
  }
}); 

module.exports = router;
Run Code Online (Sandbox Code Playgroud)

我做错了吗?我正在该网站上关注一个教程:https : //scotch.io/tutorials/easy-node-authentication-setup-and-local

我正在尝试使用password.js在我的网站上进行身份验证。经过数小时的努力来解决这个问题。任何帮助将不胜感激。谢谢。

jfr*_*d00 5

home.js您显示的文件将导出路由器。路由器不是您这样导入的东西:

require('./routes/adminportal/home.js')(app,passport); 
Run Code Online (Sandbox Code Playgroud)

如果您查看所指向/app/routes.js教程中的代码,则会显示与该类型的导入配合使用的文件,并且具有如下所示的导出:

 module.exports = function(app, passport) {  ...  }
Run Code Online (Sandbox Code Playgroud)

因此,尝试遵循该演示时,您似乎混合了文件。您正在导出路由器,但是尝试调用应该已经导出的函数,如上一行。

由于我看不到代码的整体布局,因此我只能告诉您,导出路由器时,您可以像这样使用它:

app.use('/someOptionalPath', require('./routes/adminportal/home.js'));
Run Code Online (Sandbox Code Playgroud)

要不就:

app.use(require('./routes/adminportal/home.js'));
Run Code Online (Sandbox Code Playgroud)

完全取决于您要执行的操作。这就是将路由器连接到Web服务器的方式。