Router.use() 需要中间件函数但未定义

Router.use() requires a middleware function but got undefined

我想使用 nodejs 制作 auth 应用程序,但出现了如标题所示的错误:(

但是 app.js 的代码已经是这样了

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session')

var app = express();

// 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(session({ 
  secret: '123456cat',
  resave: false,
  saveUninitialized: true,
  cookie: { maxAge: 60000 }
}))
app.use(express.static(path.join(__dirname, 'public')));

var registrationRouter = require('./routes/registration-route').default;
var loginRouter = require('./routes/login-route').default;
var dashboardRouter = require('./routes/dashboard-route').default;
var logoutRouter = require('./routes/logout-route');

app.use('/', registrationRouter);
app.use('/', loginRouter);
app.use('/', dashboardRouter);
app.use('/', logoutRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  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.listen(3000);

module.exports = app;

这是registration-route.js

var express = require('express');
var router = express.Router();
var db = require('../database');

// to display registration form 
router.get('/register', function(req, res, next) {
  res.render('registration-form');
});

// to store user input detail on post request
router.post('/register', function(req, res, next) {
    
    inputData ={
        username: req.body.username,
        email_address: req.body.email_address,
        password: req.body.password,
        confirm_password: req.body.confirm_password
    }
// check unique email address
var sql='SELECT * FROM registration WHERE email_address =?';
    db.query(sql, [inputData.email_address] ,function (err, data, fields) {
 if(err) throw err
 if(data.length>1){
     var msg = inputData.email_address+ "was already exist";
 }else if(inputData.confirm_password != inputData.password){
    var msg ="Password & Confirm Password is not Matched";
 }else{
     
    // save users data into database
    var sql = 'INSERT INTO registration SET ?';
   query(sql, inputData, function (err, data) {
      if (err) throw err;
           });
  var msg ="Your are successfully registered";
 }
 res.render('registration-form',{alertMsg:msg});
})
     
});
module.exports = router;

login-route.js

var express = require('express');
var router = express.Router();
var db = require('../database');
/* GET users listing. */
router.get('/login', function(req, res, next) {
  res.render('login-form');
});

router.post('/login', function(req, res){
    var email = req.body.email;
    var password = req.body.password;

    var sql='SELECT * FROM registration WHERE email_address =? AND password =?';
    db.query(sql, [email, password], function (err, data, fields) {
        if(err) throw err
        if(data.length>0){
            req.session.loggedinUser= true;
            req.session.email= email;
            res.redirect('/dashboard');
        }else{
            res.render('login-form',{alertMsg:"Your Email Address or password is wrong"});
        }
    })

})

module.exports = router;

logout-route.js

var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/logout', function(req, res) {
  req.session.destroy();
  res.redirect('/login');
});
module.exports = router;

dashboard-route.js

var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/dashboard', function(req, res, next) {
    if(req.session.loggedinUser){
        res.render('dashboard',{email:req.session.emailAddress})
    }else{
        res.redirect('/login');
    }
});
module.exports = router;

我已经看到这样的问题,但 none 的答案适用于我的案例问题 我也试过 npm clear cache --force 但没有任何改变

也已为 node_modulespackage-lock 卸载并重新安装,但总是出现相同的错误

更改所有这些:

var registrationRouter = require('./routes/registration-route').default;

删除 .default 所以你只有这个:

const registrationRouter = require('./routes/registration-route');

.default 是与 ESM 模块一起使用的东西,而不是与 CommonJS 模块一起使用的东西。


此外,您不应该再使用 var。现在是绝对的了。对这些使用 const