简体   繁体   中英

Is there a way to synchronously read the contents of HTTP request body in node.js?

So I am sending an HTTP POST request to a node.js HTTP server that's running locally. I wish to extract the JSON object from the HTTP body, and use the data it holds to do some stuff on the server side.

Here is my client app, which issues the request:

var requester = require('request');

requester.post(
        'http://localhost:1337/',
        {body:JSON.stringify({"someElement":"someValue"})}, 
        function(error, response, body){
                if(!error)
                {
                        console.log(body);
                }
                else
                {
                        console.log(error+response+body);
                        console.log(body);
                }
        }
);

Here's the server that is supposed to receive that request:

http.createServer(function (req, res) {

    var chunk = {};
    req.on('data', function (chunk) {                   
        chunk = JSON.parse(chunk);
    });

    if(chunk.someElement)
    {
            console.log(chunk);
            // do some stuff
    }
    else
    {
        // report error
    }

    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Done with work \n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

Now the issue is, since the req.on() function that has a callback extracts the POST data asynchronously, it seems like if(chunk.someElement) clause is evaluated before that is done, and so it always goes to the else clause and I am unable to do anything at all.

  • Is there a simpler way to handle this issue (by simpler, I mean: not using any other fancy libraries or modules, just pure node)?
  • Is there a synchronous function that performs the same tasks as req.on() and returns the contents of the body before I do the if(chunk.someElement) check?

You need to wait and buffer the request and parse/use the JSON on the request's 'end' event instead because there is no guarantee that all data will be received as a single chunk:

http.createServer(function (req, res) {

    var buffer = '';
    req.on('data', function (chunk) {
      buffer += chunk;
    }).on('end', function() {
      var result;
      try {
        result = JSON.parse(buffer);
      } catch (ex) {
        res.writeHead(400);
        return res.end('Bad JSON');
      }

      if (result && result.someElement)
      {
        console.log(chunk);
        // do some stuff
      }
      else
      {
        // report error
      }

      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end('Done with work \n');
    }).setEncoding('utf8');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM