How do I access HTTP POST data from meteor?
Asked Answered
N

1

8

I have an Iron-router route with which I would like to receive lat/lng data through an HTTP POST request.

This is my attempt:

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));
    }
  });
});

But querying the server with:

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

Returns {}.

Maybe params doesn't contain post data? I tried to inspect the object and the request but I can't find it.

Negativism answered 11/2, 2014 at 0:55 Comment(0)
P
14

The connect framework within iron-router uses the bodyParser middleware to parse the data that is sent in the body. The bodyParser makes that data available in the request.body object.

The following works for me:

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));
    }
  });
});

This gives me:

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

Also see here: http://www.senchalabs.org/connect/bodyParser.html

Propagandist answered 11/2, 2014 at 5:52 Comment(1)
request.body is what I was looking for.. Thanks!Negativism

© 2022 - 2024 — McMap. All rights reserved.