如何从Meteor中访问HTTP POST数据?

8

我有一个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 没有包含POST数据?我尝试检查对象和请求,但是找不到它。

1个回答

14

connect framework 在 iron-router 中使用 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


我正在寻找的是 request.body.. 谢谢! - gozzilli

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接