8

我有一个 Iron-router 路由,我想通过 HTTP POST 请求接收 lat/lng 数据。

这是我的尝试:

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不包含发布数据?我试图检查对象和请求,但找不到。

4

1 回答 1

14

Iron-router 中的连接框架使用 bodyParser 中间件来解析在 body 中发送的数据。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

于 2014-02-11T05:52:39.373 回答