create a http server and read the request body as json in javascript

To create an HTTP server in Node.js, you can use the built-in http module. Here is an example:

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

const server = http.createServer((req, res) => {
  // Set response headers
  res.setHeader('Content-Type', 'application/json');
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'POST');

  if (req.method === 'POST') {
    let body = '';
    req.on('data', chunk => {
      body += chunk.toString();
    });
    req.on('end', () => {
      try {
        const data = JSON.parse(body);
        // Handle the JSON data as needed
        res.end(JSON.stringify({message: 'Request received', data}));
      } catch (error) {
        res.statusCode = 400;
        return res.end(`Error: ${error.message}`);
      }
    });
  } else {
    res.statusCode = 404;
    res.end();
  }
});

const port = 3000;

server.listen(port, () => {
  console.log(`Server running on port ${port}`);
});
862 chars
35 lines

This creates a simple HTTP server that listens on port 3000. When a POST request is received, it reads the request body as a string and parses it as JSON. If parsing succeeds, it sends a response containing the parsed data. If parsing fails, it sends an error response.

To test this, you can use a tool like Postman to send a POST request with a JSON body to http://localhost:3000. The response should contain the message "Request received" and the data you sent.

gistlibby LogSnag