2017-04-02 47 views
0

所以我們可以說,我們有以下網址:如何訪問URL段(收費)ExpressJS

http://example.com/shops/map/search 

我要訪問的第二部分(地圖),並檢查它的值。 如何在Express中實現此目的?提前致謝!

+0

一般而言,[路線參數](http://expressjs.com/en/guide/routing.html#route-parameters)可用於這一點。你有沒有相關的代碼可以分享? –

+0

當我想通過id訪問實體時,我正在使用路由參數。但在我的情況下,我只需要知道第二段是地圖還是列表。它們都是硬編碼的。我的問題現在更清楚了嗎? – Codearts

+0

更好,但不完全。如果它們是硬編碼/常量,那麼路由處理程序不知道同一個常量有什麼原因嗎?你是否重複使用兩個路由的單個處理程序? –

回答

2

您可以通過將url拆分爲數組來訪問url段。 像這樣:

let requestSegments = req.path.split('/'); 
1

您可以使用具有一組常數值的路徑參數。

Express使用path-to-regexp解析您爲路由提供的字符串。該包permits providing a custom pattern帶有一個參數來限制可以匹配的值。

app.get('/shops/:kind(list|map)/search', searchShops); 

括號,(...)的內容,是一個局部正則表達式模式,在這種情況下,等同於:

/(?:list|map)/ 
# within a non-capturing group, match an alternative of either "list" or "map" literally 

然後,內searchShops,可以確定哪個值,用req.params給出:

function searchShops(req, res) { 
    console.log(req.params.kind); // 'list' or 'map' 
    // ... 
} 

或者,您可以樂AVE參數打開,檢查處理程序中的值,並調用next('route')當該值是不能接受的:

app.get('/shops/:kind/search', searchShops); 

var searchKinds = ['list', 'map']; 

function searchShops(req, res, next) { 
    if (!searchKinds.includes(req.params.kind)) return next('route'); 

    // ... 
} 
3

你有你的快遞線路配置爲接受URL段。

app.get('/shops/:type/search', function (req, res) { 
    res.send(req.params) 
}) 

對於這樣 http://example.com/shops/map/search

req.params的請求將包含所需的URL段。

Request URL: http://example.com/shops/map/search 
req.params: { "type": "map" }