create a http server and parse cookies and return a json response in javascript

Here's an example code snippet that creates an HTTP server, parses cookies from incoming requests, and returns a JSON response:

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

// create server
const server = http.createServer((req, res) => {
  // parse cookies
  const cookies = {};
  const cookieHeader = req.headers['cookie'];
  if (cookieHeader) {
    cookieHeader.split(';').forEach((cookie) => {
      const parts = cookie.split('=');
      cookies[parts.shift().trim()] = decodeURI(parts.join('='));
    });
  }

  // set response header
  res.setHeader('Content-Type', 'application/json');

  // create response object
  const response = {
    message: 'Hello World!',
    cookies: cookies
  };

  // end response with JSON string
  res.end(JSON.stringify(response));
});

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

In this example, we first create an HTTP server using http.createServer(). Then, we parse the cookies from the incoming request headers using a simple cookie parser.

Next, we set the response header to application/json and create a response object containing a greeting message and the parsed cookies. Finally, we end the response by sending the JSON stringified response object using res.end().

The server listens on port 8080 using server.listen().

gistlibby LogSnag