Reputation: 3855
I'm building my first real Express.js app, and stuck on the routing.
I am enabling static hosting:
app.use("/", express.static("public"));
And then I have a wildcard route:
router.get("/:page", function(req, res) {
// do stuff
});
This route is matching for urls like "/about
" and "/contact
" - which I want. But it appears that it's also trying to match for "/style.css
" and other static asset files - which is unnecessary.
How do I make this wildcard not match for asset files?
Upvotes: 5
Views: 2427
Reputation: 1213
if I understand what you want to do ,you should just do something like :
app.js
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/static'));
app.use('/:page',function(){}..)
this configuration works when ur public and static folder is relative to app.js, when browser request for static file , first server will look at public folder , if file is no there will continue to static folder and finally to /:page
Upvotes: -1
Reputation: 3855
One solution I found, is to search for a "." inside the query and then set a flag if it's found:
router.get("/:page", function(req, res) {
if (req.render_view) res.render("index");
});
router.param("page", function(req, res, next, page) {
// if request is not an asset file
if (page.indexOf(".") == -1) {
// do stuff
// set a flag
req.render_view = true;
}
next();
});
But I would like to find a cleaner solution, possibly using a regular expression in the router.get?
Upvotes: 2