Вопрос

For outgoing HTTP requests (using meteor.http.call) I can define params and/or data. The results are then available (via results.content).

How do I access and parse the body/contents/data of incoming HTTP requests?

Using iron-router, I have got as far as this:

Router.map(function () {
this.route('httpTest', {
path: '/httpTest',
action: function () {
  var request = this.request;
  var response = this.response;      
  console.log('request_body: '+ request.body);
  // request.body does not work.  what should it be????

N.B. I understand that I CAN access query parameters, but I want to access form data and/or json data from the body of an incoming http request.

Это было полезно?

Решение 2

It may not be working because of the missing where: 'server'. Here is a working example:

Router.map(function() {
  this.route('test', {
    where: 'server',
    action: function() {
      console.log(this.request.body.make);
      console.log(this.request.body.model);
      this.response.writeHead(200, {'Content-Type': 'text/html'});
      this.response.end('hello!\n');
    }
  });
});

From the command line I can hit this route with:

curl -X POST -H "Content-Type: application/json" -d '{"make":"honda","model":"civic"}' http://localhost:3000/test

Which prints the expected honda and civic in the server's terminal. It looks like this.request.body is already parsed so you can access any variables directly which is nice if your input is json.

Другие советы

The request is an incoming http message, which is a Readable Stream, so you can get the data of the request by reading from that stream.

The following should work (but I haven't tested it):

var readable = this.request;
var alldata = "";
readable.on('data', function(chunk) {
  alldata += chunk;
})
readable.on('end', function() {
  console.log('do something with alldata');
});

To read the raw body, without having Node.js JSON-ify it, in a synchronous way, I used this:

Router.route("my/api", function() {
    var rawBody = "";
    var chunk;
    while ((chunk = this.request.read()) !== null) {
        rawBody += chunk;
    }
}, { where: "server" });

(the asynch way proposed in another answer here didn't worked for me, although it should as per Node.js documentation).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top