Kob_24 Kob_24 - 6 months ago 34
Node.js Question

Deny access to specific directory in nodejs express

I am trying to deny public to see files in a special directory using node express following is the code:

app.use(express.static(path.join(__dirname, 'partials')));

app.all('/partials/*', function (req,res, next) {

res.status(403).send(
{
message: 'Access Forbidden'
});
next();
});


If i route to localhost/partials, i get the message 'Access Forbidden' But not if i route to localhost/partials/files.html

Any recommendations?

Answer

Order of statements matter in node.js.

app.all('/partials/*', function (req,res, next) {
   res.status(403).send({
      message: 'Access Forbidden'
   });
});

//this line is used to load resources at localhost/partials/api.html
//but, because of above code snippets, we have blocked /partials/* routes
//hence, this line will practically wont work.
app.use('/partials',express.static(path.join(__dirname, 'partials')));