简体   繁体   中英

ExpressJS - Optional part of the URL which is not a param?

I have a route like this: /products/123/versions/456 .

I want the sub resource to be optional, so I want one route path to handle both /products/123 and /products/123/versions/456 .

This doesn't work: /products/:pid/versions?/:vid? .

How do I make the /versions/ part optional without making it a param with : ..?

You can make a named handler and use it for two routes:

function yourhandler(req, res) {
    // ...
}
app.get('/products/:pid', yourHandler);
app.get('/products/:pid/versions/:vid', yourHandler);

Or you can fight with regular expressions and optional parts. But those are really two different routes, not one, and it just happens that you want to use the same handler for both of them so using two app.get() (or whatever HTTP method it is) route definitions is the clearest way to solve it.

You can also add this if you need it as well:

app.get('/products/:pid/versions', yourHandler);
app.get('/products/*',  (req, res, next){

const path = req.path;

//now use any logic on path as string

if(path.includes('versions')){

console.log('run version handler');

}else{
console.log('run else handler')}

}

//or const [product, version] = /\/products\/(.*)\/versions\/(.*)/.exec(path)
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM