Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
945 views
in Technique[技术] by (71.8m points)

json - How do I access HTTP POST data from meteor?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...