create a http server and read the request body as form url encoded in javascript

To create an HTTP server in Node.js and read the request body as form-urlencoded, use the built-in http module and the querystring module.

Here's an example:

index.tsx
const http = require('http');
const querystring = require('querystring');

const server = http.createServer((req, res) => {
  if (req.method === 'POST' && req.headers['content-type'] === 'application/x-www-form-urlencoded') {
    let body = '';
    req.on('data', chunk => {
      body += chunk.toString();
    });
    req.on('end', () => {
      const data = querystring.parse(body);
      console.log(data);
      res.end('Received form-urlencoded data'); // send response
    });
  } else {
    res.end('Hello World!'); // send response
  }
});

server.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
639 chars
23 lines

In this example, the server listens on port 3000 for incoming HTTP requests. The server checks if the HTTP method is POST and the content-type is application/x-www-form-urlencoded. If both conditions are true, the server reads the request body using req.on('data') and req.on('end'), parses the data using querystring.parse(), and logs it to the console.

Finally, the server sends a response back to the client using res.end(). If the HTTP method is not POST or the content-type is not application/x-www-form-urlencoded, the server sends a generic "Hello World!" response.

gistlibby LogSnag