Node.js Express REST API - 使用GET请求访问JSON url params

时间:2014-07-27 19:30:32

标签: json node.js rest express get

我有一个REST端点,它是/ geo / search,需要一些长/纬坐标作为请求(GEO多边形)的一部分发送。

  • 我有什么办法可以在GET请求中使用JSON吗?我在想这个URL编码可能是一个解决方案:

    var data = encodeURIComponent({"coordinates":[[-122.610168,37.598167],[-122.288818,37.598167],[-122.288818,37.845833],[-122.610168,37.845833],[-122.610168,37.598167]]});
    
  • 我如何在路线中访问这些参数?

1 个答案:

答案 0 :(得分:1)

回答#1 - 感谢@mccannf

使用JQuery.param:

客户端:

var test = {"coordinates":[[-122.610168,37.598167],[-122.288818,37.598167],[-122.288818,37.845833],[-122.610168,37.845833],[-122.610168,37.598167]]};

    console.log($.param( test ));

输出:

coordinates%5B0%5D%5B%5D=-122.610168&coordinates%5B0%5D%5B%5D=37.598167&coordinates%5B1%5D%5B%5D=-122.288818&coordinates%5B1%5D%5B%5D=37.598167&coordinates%5B2%5D%5B%5D=-122.288818&coordinates%5B2%5D%5B%5D=37.845833&coordinates%5B3%5D%5B%5D=-122.610168&coordinates%5B3%5D%5B%5D=37.845833&coordinates%5B4%5D%5B%5D=-122.610168&coordinates%5B4%5D%5B%5D=37.598167 

回答#2 - 感谢@Brad:

服务器 - 快速路线:

router.get('/search_polygon', function(req, res) {
    console.log('Server received: ' + JSON.stringify(req.query.coordinates));
...

输出:

Server received: [["-122.610168","37.598167"],["-122.288818","37.598167"],["-122.288818","37.845833"],["-122.610168","37.845833"],["-122.610168","37.598167"]]

我的问题是尝试将这些作为路径的一部分传递,而不是作为参数传递。