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.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) {

app.get(__dirname + '/PUBLIC/important.json', function(req, res) {

app.get('important.json', function(req, res) {

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) => {
app.use(express.static(__dirname + '/PUBLIC'));