我正在尝试在Express中构建configurable middleware(一个接受自定义参数并返回使用这些参数的(req,res,next)
函数的自定义中间件函数)。但是,我无法让此中间件在router.get()
调用中执行。
下面的代码中的预期行为是,当尝试获取主页(/)时,控制台将记录“成功!”。然后我得到一个404(因为中间件中的next()
会将我传递给404函数)。
但是,什么也没有发生,并且请求超时。正在检测该功能,因为当我将console.log()
放在中间件中但就在return function(req,res,next){
行之前时,我正在控制台上看到输出。仅当可配置中间件返回一个函数时,我才遇到此问题。
./ app.js (对Express构建的模板没有更改):
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
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('/', indexRouter);
app.use('/users', usersRouter);
// 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');
});
module.exports = app;
./ routes / index.js :
var express = require('express');
var router = express.Router();
var simplemiddleware = require('../middlewares/simplemiddleware');
/* GET home page. */
router.get('/', function(req, res, next) {
simplemiddleware.simpleReturn('success!');
});
module.exports = router;
./ middlewares / simplemiddleware.js :
exports.simpleReturn = function (outputString){
return function (req,res,next) {
console.log(outputString);
next();
}
}
答案 0 :(得分:0)
请注意
var simplemiddleware = require('../middlewares/simplemiddleware');
实际上是function
,要解决此问题,请尝试以下操作。
./ routes / index.js:
var simplemiddleware = require('../middlewares/simplemiddleware');
/* GET home page. */
router.get('/', function(req, res, next) {
// note `simplemiddleware.simpleReturn(str)` returns a function
let func = simplemiddleware.simpleReturn('success!');
// run the middleware
func(req, res, next);
});