使用Express模块​​作为中间件

我是Express的新手,尝试使用中间件来处理POST请求。 如果我暴露端点,并向API发出请求,一切工作正常。


正确地工作

API / index.js

app.post('/api/endpoint', (req, res, next) => { next(); }); 

server.js

 app.use(function() { console.log('hello'); // => hello }); 

但是,当我尝试用导出函数的模块replace中间件函数时,该函数永远不会被调用。


不工作

API / index.js

 app.post('/api/endpoint', (req, res, next) => { next(); }); 

server.js

 const makeExternalRequest = require('./server/makeExternalRequest'); ... console.log(makeExternalRequest, typeof makeExternalRequest); // => [Function] 'function' app.use(makeExternalRequest); 

服务器/ makeExternalRequest.js

 module.exports = function(err, req, res, next) { console.log('hello', err); } 

server / makeExternalRequest.js中的function从来没有被调用,没有logging…我使用app.use(...)不正确?

Express中间件需要三个参数,其中第三个参数是您在完成将请求移动到下一个处理程序时所调用的函数:

 module.exports = function (req, res, next) { console.log('hello'); next(); }; 

在不调用第三个参数的情况下,您的请求将保持悬而未决,并且永远不会发送响应。 另外,请确保在任何将返回响应的处理程序之前调用app.use。 如果首先发送响应,那么您的中间件将永远无法到达。