Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
709 views
in Technique[技术] by (71.8m points)

node.js - Exclude sub directory from static files in express

Is there any way to exclude sub directory from express static middleware in express 4.8.5.

For example if I have :

app.use(express.static(__dirname + 'public'));

And my public directory is like this :

- public  
   - css
   - images
   - scripts
   - index.html
   - exclude_me
        - scripts
        - views
        - index.html

So I need to exclude last sub directory and when user does :

GET /exclude_me

It should call my route rather than returning directory automatically.

I can't just remove it from public dir because it depends on stuff inside it because public directory is angular application and exclude_me is another angular application that fetches scripts from /exclude_me/scripts AND from /public/scripts.

I know it is little confusing but it is how it is and I cannot just remove it from public dir because it won't see public/scripts any more which are needed and I cannot leave it because I cannot authorize it then (all authorization is in public/scripts)

If there is some smarter way to do this, feel free to let me know :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can add your own middleware. Here's what I did to exclude some folders:

app.use('/public', (req, res, next) => {
  if (env !== 'development') {
    var result = req.url.match(/^/js/(maps|src)/.+.js$/)
    if (result)?{
      return res.status(403).end('403 Forbidden')
    }
  }
  next()
})
app.use('/public', express.static(path.join(__dirname, '/public')))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...