Home > Back-end >  Express serve static file and run piece of code at /
Express serve static file and run piece of code at /

Time:10-20

I need to serve a folder of static files containing HTML and js which I achieve by

app.use('/', express.static('./public'));

I also need to run a piece of code whenever user enters the site, which I try to accomplish by

app.get('/', function (req, res) { // Piece of code });

But the piece of code doesn't executed

how to achieve them both

CodePudding user response:

Have the middleware with the piece of code first and end it with a call of next(). This will pass control to the next middleware, that is, the express.static one:

app.get('/', function (req, res, next) {
  // Piece of code
  next();
});
app.use('/', express.static('./public'));

CodePudding user response:

Express will not reach the next middleware in your case.

I would wrap the middleware function with a custom one.

const serveStatic = express.static('./public')
app.get('/',(req, res, next) => {
 // do here what you want

 // then call the static serve method
 serveStatic(req, res, next)
}
)
  • Related