Skip to content

Instantly share code, notes, and snippets.

@wilmoore
Last active August 3, 2024 17:07
Show Gist options
  • Select an option

  • Save wilmoore/29f9f6f05ab19f9efca47325ee8ad309 to your computer and use it in GitHub Desktop.

Select an option

Save wilmoore/29f9f6f05ab19f9efca47325ee8ad309 to your computer and use it in GitHub Desktop.
Software Engineering :: Programming :: Languages :: JavaScript :: Runtimes :: Node.js :: HTTP :: Server :: About :: Anatomy of an HTTP Transaction

Software Engineering :: Programming :: Languages :: JavaScript :: Runtimes :: Node.js :: HTTP :: Server :: About :: Anatomy of an HTTP Transaction

⪼ Made with 💜 by Polyglot.

related
const http = require('node:http');

http
  .createServer((request, response) => {
    const { headers, method, url } = request;
    let body = [];
    request
      .on('error', err => {
        console.error(err);
      })
      .on('data', chunk => {
        body.push(chunk);
      })
      .on('end', () => {
        body = Buffer.concat(body).toString();
        // BEGINNING OF NEW STUFF

        response.on('error', err => {
          console.error(err);
        });

        response.statusCode = 200;
        response.setHeader('Content-Type', 'application/json');
        // Note: the 2 lines above could be replaced with this next one:
        // response.writeHead(200, {'Content-Type': 'application/json'})

        const responseBody = { headers, method, url, body };

        response.write(JSON.stringify(responseBody));
        response.end();
        // Note: the 2 lines above could be replaced with this next one:
        // response.end(JSON.stringify(responseBody))

        // END OF NEW STUFF
      });
  })
  .listen(8080);


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment