拒绝访问nodejs express中的特定目录

时间:2016-05-26 10:05:59

标签: node.js express routes

我试图拒绝公众使用node express查看特殊目录中的文件,代码为:

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

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

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

如果我路由到localhost / partials,我收到消息' Access Forbidden'但是,如果我路由到localhost / partials / files.html

有什么建议吗?

1 个答案:

答案 0 :(得分:5)

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