2014-01-29 39 views
5

我有兩條獲取商店的GET路線,但是,一條路線用於獲取所有商店,另一條路線用於獲取附近的商店。使用搜索參數快速路由GET

1)獲得所有商店的URL請求如下:

http://mydomain/stores 

2)的網址,讓所有附近的商店:

http://mydomain/stores?lat={lat}&lng={lng}&radius={radius} 

的問題是:

如何我可以在Express中正確映射這些網址,以便將每個路由重定向到相應的方法嗎?

app.get('/stores', store.getAll); 

app.get('/stores', store.getNear); 

回答

11
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) 
+0

請注意,如果緯度/經度/半徑是零,因爲這是falsy這將失敗;如果這是一個問題,你可以明確地測試'undefined' – Plato

+0

我的想法是避免使用,但如果沒有另一種方式,沒關係! – vitorvigano

+0

我發佈了一種替代方法,但爲什麼你會希望能夠在相同的路線上運行不同的功能,取決於沒有「if」的情況? – Plato