admin管理员组文章数量:1401849
I'm looking to find out if it's possible to serve only one type of file (filtered by extension) out of an Express.js static directory.
For example, let's say I have the following Static directory:
Static
FileOne.js
FileTwo.less
FileThree.html
FileFour.js
And say I want to make only files with a .js
extension available to any given request, and all other requests would get a 500 response (or something like that).
How would I go about achieving this? Does Express have a baked-in filter that I haven't been able to find, or do I need to use regular expressions?
I'm looking to find out if it's possible to serve only one type of file (filtered by extension) out of an Express.js static directory.
For example, let's say I have the following Static directory:
Static
FileOne.js
FileTwo.less
FileThree.html
FileFour.js
And say I want to make only files with a .js
extension available to any given request, and all other requests would get a 500 response (or something like that).
How would I go about achieving this? Does Express have a baked-in filter that I haven't been able to find, or do I need to use regular expressions?
Share Improve this question asked Mar 13, 2014 at 23:29 AJBAJB 7,60015 gold badges60 silver badges91 bronze badges 02 Answers
Reset to default 6I use
app.get(/static\/.*js$/, function(r, s){
or
app.get('*', function(r, s){
if(r.url.match(/.*js$/)) // then serve
})
Doesn't appear to me that you can configure the "static" middleware in this way. In the "serve-static" module, which is the replacement for "static" for Express 4.0 (currently in RC stage), there are some options, but not filtering.
If you want just to serve *.js files, you can create a route yourself. Create an app.get('/static/*')
that responds with the file content and proper mime type, if the requested file is .js.
An alternative is to fork the "static" module, or better the new "serve-static", so it fits your needs. For example, you could create a new library copying the contents of this file, and after the line
var originalUrl = url.parse(req.originalUrl);
You may add something like
if(originalUrl.slice(-3) != '.js') return next();
This should ignore (calling the next middleware) all requests for static files that aren't ending in ".js". (untested, but it's inspired by the code above)
With the code above, create a new library (e.g. save it in "lib/my-static.js") and include it:
app.use(require('lib/my-static'))
本文标签: javascriptServe only js files from an Express static directoryStack Overflow
版权声明:本文标题:javascript - Serve only .js files from an Express static directory? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744291591a2599139.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论