javascript TypeError:无法读取Express架构之未定义的属性'apply'

xxe27gdn  于 2022-12-10  发布在  Java
关注(0)|答案(2)|浏览(125)

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;

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

// 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);
        });

    }));
};

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;

我是不是做错了?我是按照这个网站上的教程:https://scotch.io/tutorials/easy-node-authentication-setup-and-local
我正在尝试使用passport.js在我的网站上做身份验证。一直在努力几个小时来解决这个问题。任何帮助将不胜感激。谢谢。

oug3syen

oug3syen1#

您显示的home.js文件导出了一个路由器。路由器不是您这样导入的:

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

如果您查看指向的tutorial/app/routes.js的代码,就会看到使用该导入类型的文件,它的导出如下所示:

module.exports = function(app, passport) {  ...  }

所以,你看起来有文件混淆时,试图遵循该演示。你正在导出一个路由器,但试图调用一个函数,应该已经导出,如上面的行。
由于我无法看到代码中的整体布局,我所能告诉您的是,当您导出一个路由器时,您可以这样使用它:

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

或仅:

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

这取决于你想做什么。这就是你如何将路由器连接到你的网络服务器。

6tqwzwtp

6tqwzwtp2#

我发现了以下错误

/www/wwwroot/domain.com/node_modules/express/lib/router/index.js:646
return fn.apply(this, arguments);
          ^

类型错误:无法在“立即”处读取未定义的属性“apply”。(/www/wwwroot/domain. com/node_modules/express/lib/router/index. js:646:15)在处理“立即”时(internal/timers.js:466:21)
并且通过将中的return fn.apply(this, arguments);替换为return (fn?.apply(this, arguments)) ? fn.apply(this, arguments) : '';来解决
希望它能拯救一些人

相关问题