mafintosh / turbo-http

Blazing fast low level http server
MIT License
1k stars 47 forks source link

request.onData is not getting triggered #25

Open KiranRamashetty opened 5 years ago

KiranRamashetty commented 5 years ago

In request Construction the ondata is being to empty function

  this.ondata = noop
  this.onend = noop

In server.js

parser[HTTPParser.kOnBody] = onbody

function onbody (body, start, end) {
     req.ondata(body, start, end)
}

So wondering if I am missing something here? How to do I receive POST data?

lucagez commented 5 years ago

Hi, I am pretty late but I will add it anyway. Here is a snippet for reading the body of a request.

const _body = req => new Promise(resolve => {
  const parts = [];
  req.ondata = (buffer, start, length) => {
    const part = buffer.slice(start, length + start).toString();
    parts.push(part);
  };

  req.onend = () => resolve(parts.join(''));
});

Then you can use it in your server like that:

const http = require('turbo-http');
const server = http.createServer().listen(3000);

server.on('request', async (req, res) => {
  const body = await _body(req);
  res.end();
});
dalisoft commented 5 years ago

@lucagez You saved my hours. @mafintosh Maybe we should add this snippet to documentation?