mkto mkto - 1 year ago 131
Node.js Question

Intercept request for a static file in express.js

I have a node server, that serves static files in a PUBLIC folder like this:

var app = express();
app.listen(port);
app.use(compression());
app.use(express.static(__dirname + '/PUBLIC'));


There is a json file, let's say important.json that is located in /PUBLIC folder. This is being served as a static file

Now, I want to intercept request for this /PUBLIC/important.json, so that I can programatically return a random json structure instead.

None of the followings works:

app.get('/PUBLIC/important.json', function(req, res) {
console.log("caught1!")
});

app.get(__dirname + '/PUBLIC/important.json', function(req, res) {
console.log("caught2!")
});

app.get('important.json', function(req, res) {
console.log("caught3!")
});


How can I intercept request for that partically static file?

str str
Answer Source

As the express.static middleware does not call the next middleware using next(), the definition order is important. You have to define your own middleware before using express.static.

app.get('/PUBLIC/important.json', (req, res, next) => {
    console.log('caught');
    next();
});
app.use(express.static(__dirname + '/PUBLIC'));