create a http server and read the request body in javascript

To create a HTTP server and read the request body in JavaScript, you need to use the built-in http module in Node.js and a middleware package like body-parser:

index.tsx
const http = require('http');
const bodyParser = require('body-parser');

const server = http.createServer((req, res) => {
  if (req.method === 'POST') {
    // parse application/x-www-form-urlencoded
    bodyParser.urlencoded({ extended: false })(req, res, () => {
      console.log(req.body);
      res.end('Request body received.');
    });
  } else {
    res.end('Hello, world!');
  }
});

server.listen(3000, () => {
  console.log('Server listening on port 3000.');
});
475 chars
19 lines

In this example, we first create an HTTP server using http.createServer(). When we receive a request, we check if it's a POST request. If it is, we use body-parser to parse the request body and log it to the console. If it's not a POST request, we simply send a response of "Hello, world!".

Note that we're using bodyParser.urlencoded() to parse application/x-www-form-urlencoded requests. If you need to parse another format (such as JSON), you'd use a different method from the body-parser package.

gistlibby LogSnag