In Express.js, how do I set a wildcard pattern that does not match asset files?

I am building my first Express.js application and am stuck with routing.

I provide static hosting:

app.use("/", express.static("public"));

And then I have a wildcard pattern:

router.get("/:page", function(req, res) {
    // do stuff
});

This route is suitable for the URLs such as " /about" and " /contact" that I want. But it looks like he is also trying to match " /style.css" and other static asset files, which is not necessary.

How to make this template not match asset files?

+4
source share
2 answers

, , - ".". , , :

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

});

, , router.get?

+2

, , - :

app.js

 app.use(express.static(__dirname + '/public'));
 app.use(express.static(__dirname + '/static'));
 app.use('/:page',function(){}..)

, ur app.js, , , , , , /: page

-1

Source: https://habr.com/ru/post/1613994/


All Articles