【发布时间】:2020-09-14 15:37:05
【问题描述】:
错误:Route.get() 需要回调函数但得到了 [object Undefined] 我尝试在 VS-code 上运行该应用程序,并收到此消息
/home/unkown/Node/node_modules/express/lib/router/route.js:202
throw new Error(msg);
^
Error: Route.get() requires a callback function but got a [object Undefined]
at Route.<computed> [as get] (/home/unkown/Node/node_modules/express/lib/router/route.js:202:15)
我更新到最新版本的软件包并重新启动端口,但仍然显示此错误。
地狱在哪里?请
我的代码
节点/app.js
const express = require('express');
const path = require('path');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const index = require('./app_server/routes/index');
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'app_server', 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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');
});
module.exports = app;
Node/app_server/controllers/locations.js
/* GET 'home' page */
const homeList = (res, req)=>{
res.render('index', {title: 'Home'})
};
/* GET 'Location info' page */
const locationInfo = (res, req)=>{
res.render('index', {title: 'Location Info'})
};
/* GET 'Add review' page */
const addReview = (res, req)=>{
res.render('index', {title: 'Add Review'})
};
module.exports = {
homeList,
locationInfo,
addReview
};
Node/app_server/router/index.js
const express = require('express');
const router = express.Router();
const ctrlLocations = require('../controllers/locations');
const ctrlOthers = require('../controllers/others');
/* Locations pages */
router.get('/', ctrlLocations.homelist);
router.get('/location', ctrlLocations.locationInfo);
router.get('/location/review/new', ctrlLocations.addReview);
/* Other pages */
router.get('/about', ctrlOthers.about);
module.exports = router;
【问题讨论】:
-
users中的app.use('/users', users);是什么 -
const homeList = (res, req)将其更改为const homeList = (req, res)所有路线都一样 -
代码的哪一行发生了这个错误?您必须回顾堆栈跟踪并查看它在您的某个文件中的位置,可能是
index.js。这会告诉你哪个路由定义是错误的。由于您没有显示ctrlOthers的代码,我猜router.get('/about', ctrlOthers.about);可能是罪魁祸首,但也可能是您没有向我们展示的其他代码。 -
@jfriend00 我现在隐藏了这段代码,但还是一样。是的,我隐藏了一些资源,但不是必需的,例如带有 .pug 的视图/。
-
@Yousaf 这是另一个空文件。