Bálint Réthy
Bálint Réthy

Reputation: 433

Nodejs express regex routing with variable in it - why does not match?

I am using express 4.16 and I want to create a route that accepts every path with a variable at the end.

I tried something like this but it does not match :S

 ...
    router.get('/.*:name$/', (req, res) => {
    ...

for example:

.../animal/Joe
.../fruit/apple.txt
.../people/man/Sam

I used this page to test it: http://forbeslindesay.github.io/express-route-tester/

Edit 1 ----------------- So as I mentioned I am trying to create an svg api that gives back a public svg file in a different color. Example: localhost:3000/svg/logo/logo.svg?color=#232323

server.js:

..
const svg = require('./server/routes/svg');
...
app.use('/svg', svg);
...

svg.js

const express = require('express');
const router  = express.Router();
var   fs      = require('fs');

router.get('/.*:name$/', (req, res) => {
    let name  = req.params.name;
    let color = req.query.color;
    console.log(req.path, color, req.originalUrl, req.path);
    if(typeof name != 'undefined' && typeof color != 'undefined'){
        res.setHeader('Content-Type', 'image/svg+xml');
        //                  here I should concatenate req.path before name or something like this idk..
        let read = fs.readFile(`${__dirname}/../../dist/assets/images/svg/${name}.svg`, 'utf8', (err, template) => {
            if(typeof template !== 'undefined'){
                let svg = template.replace(/\#000000/g, (match) => {
                    return color;
                });
                return res.send(svg);
            }else{
                return res.status(404).send();
            }
        });
    }else{
        return res.status(404).send();
    }
});

module.exports = router;

(This code is not compleate I just stuck with the router)

Thanks your time in advance! :)

Upvotes: 0

Views: 1730

Answers (2)

Rodrigo Ferreira
Rodrigo Ferreira

Reputation: 1101

After playing with Express Route Tester I came up with this pattern:

*/:name

According to the Route Tester, this pattern will be compiled (valid for path-to-regexp 0.1.7) into the following regular expression:

/^(.*)\/(?:([^\/]+?))\/?$/i

^(.*) will capture everything from the start

([^\/]+?) will capture and store the last value into name

Note: Is important to observe that * is compiled to (.*).

For the latest version of path-to-regexp the following pattern should be equivalent:

(.*)/:name

Hope it helps!

Upvotes: 2

Paul
Paul

Reputation: 36339

Against my better judgement, you can do what you're looking for with a regex that is not named.

router.get('/svg/path/(.*)', (req, res) => {
  // in here, you'll get the full path with req.path and then parse it validate it's the right form and to get the info you need out of it.

  // You can also use req.query to get the color param you mentioned.  
});

Upvotes: 0

Related Questions