简体   繁体   中英

Express.js route and regex

I have an object like this :

geo: {
        description: 'Geolocalisation',
        properties: {
            latitude: {type: 'number'},
            longitude: {type: 'number'}
        }
    }

I want to create routes to retrive a nested object like :

host/geo.schema or host/geo.json

to get the entire object

host/geo/properties.schema or host/geo/properties.json

to get

properties: {
            latitude: {type: 'number'},
            longitude: {type: 'number'}
        }

You could try the following:

var geo = {
    description: 'Geolocalisation',
    properties: {
        latitude: {type: 'number'},
        longitude: {type: 'number'}
    }
}

app.get('/host/geo.(schema|json)', function (req, res, next) {
  return res.status(200).json(geo);
});

app.get('/host/geo/properties.(schema|json)', function (req, res, next) {
  return res.status(200).json(geo.properties);
});

I found a solution with regex.

app.get('\/[a-zA-Z]+(\/[a-zA-Z]*)+(\.json|\.schema)', function (req, res) {
        var url = req.url.toLowerCase();

        var elements = url.split('/');
});

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