我有一个Iron-router路由,我想通过它通过HTTP POST请求接收经纬度数据。

这是我的尝试:

Router.map(function () {
  this.route('serverFile', {
    path: '/receive/',
    where: 'server',

    action: function () {
      var filename = this.params.filename;
      resp = {'lat' : this.params.lat,
              'lon' : this.params.lon};
      this.response.writeHead(200, {'Content-Type': 'application/json; charset=utf-8'});
      this.response.end(JSON.stringify(resp));
    }
  });
});


但是查询服务器:

curl --data "lat=12&lon=14" http://127.0.0.1:3000/receive


返回{}

也许params不包含发布数据?我试图检查对象和请求,但找不到。

最佳答案

iron-router中的connect framework使用bodyParser中间件来解析正文中发送的数据。 bodyParser使该数据在request.body对象中可用。

以下对我有用:

Router.map(function () {
  this.route('serverFile', {
    path: '/receive/',
    where: 'server',

    action: function () {
      var filename = this.params.filename;
      resp = {'lat' : this.request.body.lat,
              'lon' : this.request.body.lon};
      this.response.writeHead(200, {'Content-Type':
                                    'application/json; charset=utf-8'});
      this.response.end(JSON.stringify(resp));
    }
  });
});


这给了我:

> curl --data "lat=12&lon=14" http://127.0.0.1:3000/receive
{"lat":"12","lon":"14"}


另请参阅此处:
http://www.senchalabs.org/connect/bodyParser.html

09-15 15:59
查看更多