create a http server with a post route in javascript

To create an HTTP server with a POST route in JavaScript using Node.js, you can follow the below steps:

  1. Start by requiring the http module in your JavaScript file:

    index.tsx
    const http = require('http');
    
    30 chars
    2 lines
  2. Next, create the server using the http.createServer() method and specify a request listener function that will handle incoming requests:

    index.tsx
    const server = http.createServer((req, res) => {
    
       // Handle incoming requests here
    
    });
    
    91 chars
    6 lines
  3. Inside the request listener function, you can check the req.method property to determine if the incoming request is a POST request:

    index.tsx
    if (req.method === 'POST') {
    
       // Handle POST requests here
    
    }
    
    65 chars
    6 lines
  4. Now, you can read the data being sent in the request body by listening to the data event and appending the incoming data to a buffer:

    index.tsx
    let requestBody = '';
       
    req.on('data', (chunk) => {
       requestBody += chunk.toString();
    });
    
    94 chars
    6 lines
  5. Once all the data has been received, listen to the end event and process the data as needed:

    index.tsx
    req.on('end', () => {
    
       // Process the request data here
    
    });
    
    64 chars
    6 lines
  6. Finally, send a response back to the client using the res.write() and res.end() methods:

    index.tsx
    res.write('Received the POST request data');
    res.end();
    
    56 chars
    3 lines

Here's the complete code example that you can use as reference:

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

const server = http.createServer((req, res) => {

   if (req.method === 'POST') {

      let requestBody = '';
      
      req.on('data', (chunk) => {
         requestBody += chunk.toString();
      });

      req.on('end', () => {

         // Process the request data here
         console.log(requestBody);

         res.write('Received the POST request data');
         res.end();
      });
   }
   else {
      res.write('Hello World!');
      res.end();
   }

});

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

gistlibby LogSnag