Search code examples
node.jsregexexpressurlurl-routing

Express 4: How to catch param in dynamic route structured like file name?


I'm trying to use Express 4 route endpoint that has part of the route in the file URL part - file name. It's used for dynamic generated image. I think it's best described by example...


What I have right now

Right now I have something like this in my routes:

app.get('/api/listing/:id/cover.png', viewListingImage)

And e.g. this URL http://localhost:9500/api/listing/750/cover.png matches listing with id 750.

Expectations

What I would like to have is URL which last part is a filename with listing id in it. So I can quickly save it locally with that filename. E.g.

http://localhost:9540/api/listing/750-cover.png

So basically, I'd like to just replace forward slash with a hyphen.


Tried some RegEx magic, but had not luck. Thanks for any help!


Solution

  • You can use a regex in the route:

    const app = require('express')();
    
    // match /api/listing/ddd-filename
    // where ddd is a series of digits
    app.get(/\/api\/listing\/(\d+)-([^\/]+)/, function(req, res) {
        console.log(req.params);
        res.send("hello");
    });
    
    app.listen(80);
    

    Then, if you request a URL such as /api/listing/20-cover.png, you will find that in the request handler:

    req.params[0] === '20'
    req.params[1] === 'cover.png';
    

    Capture groups in the regex are put into req.params as described here.


    As I said in my comments, you could also just do:

    app.get('/api/listing/:filename', function(req, res) {
        // parse req.params.filename yourself here
    });