Himmel Himmel - 5 months ago 15
Node.js Question

Using Express module as middleware

I'm new to Express and trying to use middleware to handle a POST request. If I expose the endpoint, and make a request to the API, everything works fine.




Working Correctly



api/index.js

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


server.js

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





But when I try to replace the middleware function with a module that exports a function, the function never gets invoked.




Not Working



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


server/makeExternalRequest.js

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





The function in server/makeExternalRequest.js is never invoked, and nothing logs... Am I using
app.use(...)
incorrectly?

Answer

Express middleware requires three arguments, the third of which is a function you call when you're done to move the request along to the next handler:

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

Without calling the third parameter, your request will just remain pending and a response will never be sent. Also, be sure you call app.use before any handler that would return the response. If the response is sent first, then your middleware will never be reached.

Comments