使用search参数快速路由GET
我有两条获取商店的GET路线,但是,一条路线是为了获得所有商店,另一条路线是为了获得附近的商店。
1)获取所有商店的url请求如下:
http://mydomain/stores
2)获取所有附近商店的url:
http://mydomain/stores?lat={lat}&lng={lng}&radius={radius}
问题是:
我怎样才能将这些url正确映射到Express中,从而将每个路由redirect到相应的方法?
app.get('/stores', store.getAll); app.get('/stores', store.getNear);
app.get('/stores', function(req, res, next){ if(req.query['lat'] && req.query['lng'] && req.query['radius']){ store.getNear(req, res, next); } else { store.getAll(req, res, next) }; });
编辑 – 第二种方法来做到这一点:
store.getNear = function(req, res, next){ if(req.query['lat'] && req.query['lng'] && req.query['radius']){ // do whatever it is you usually do in getNear } else { // proceed to the next matching routing function next() }; } store.getAll = function(req, res, next){ // do whatever you usually do in getAll } app.get('/stores', store.getNear, store.getAll) // equivalent: // app.get('/stores', store.getNear) // app.get('/stores', store.getAll)