2016-12-05 28 views
0

我是Node.js和Express的新手, 我一直在研究一個RESTful API項目,並試圖發送一個帶有多個參數的GET請求:使用Express的多個GET參數

這裏是我的路線:

/centers/:longitude/:latitude 

,這裏是我如何試圖調用它:

/centers?logitude=23.08&latitude=12.12 

,我也試過

/centers/23.08/12.12 

它結束了去這條路線:

/centers/ 

所以是我寫的端點錯誤的方式?或者我要求的方式?

+0

發表你的代碼,說明你是如何打電話以及如何接收的。 –

+0

[Node.js:Express app.get可能有多個查詢參數](http://stackoverflow.com/questions/19020012/node-js-express-app-get-with-multiple-query-parameters) – WitVault

回答

1

嘗試這樣

var express = require('express'); 
var app = express(); 
var port = process.env.PORT || 8080; 
app.get('/centers/:log/:lat',function(req,res) 
     { 
res.json({ log: req.params.log, 
      lat: req.params.lat }); 

}); 
app.listen(port); 
console.log('Server started! At http://localhost:' + port); 

現在就來試試這樣http://localhost:8080/centers/55/55

enter image description here

3

您還沒有正確理解路由定義在快遞是如何工作的網址。

路由定義是這樣的:

/centers/:longitude/:latitude 

意味着它期待這樣的URL:

/centers/23.08/12.12 

當你形成這樣的URL:

/centers?longitude=23.08&latitude=12.12 

您正在使用查詢參數rs(param=value對之後的?)。要訪問這些,看到這個問題/答案:How to access the GET parameters after "?" in Express?

對於這一點,你可以爲"/centers"創建路由,然後你將訪問req.query.longitudereq.query.latitude訪問那些特定的查詢參數。