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

To create an HTTP server in Node.js, we use the built-in http module. Here's an example of creating an HTTP server that listens on port 3000:

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

const server = http.createServer((req, res) => {
  // handle incoming requests here
});

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

To read the request body as JSON, we need to handle the data and end events on the req object. Here's a complete example that parses JSON, logs it to the console, and returns a simple response:

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

const server = http.createServer((req, res) => {
  // handle incoming requests here
  if (req.method === 'POST' && req.url === '/api') {
    let data = '';
    req.on('data', chunk => {
      data += chunk;
    });
    req.on('end', () => {
      try {
        const body = JSON.parse(data);
        console.log(body);
        res.setHeader('Content-Type', 'application/json');
        res.end(JSON.stringify({ status: 'success' }));
      } catch (e) {
        res.statusCode = 400;
        return res.end(`Error: ${e.message}`);
      }
    });
  } else {
    res.statusCode = 404;
    return res.end('Not Found');
  }
});

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

This example handles only POST requests to the /api endpoint, and assumes that the request body is a valid JSON string. The response body simply returns a JSON object with a status property set to 'success'. If the request body can't be parsed as JSON, the server returns a 400 status code and an error message.

This is just a basic example, but it should give you a starting point for creating an HTTP server with JSON parsing and response.

gistlibby LogSnag