Skip to content

Instantly share code, notes, and snippets.

@aungthuoo
Last active June 24, 2024 04:26
Show Gist options
  • Save aungthuoo/e6404fda5cb375670335010fffcb53d4 to your computer and use it in GitHub Desktop.
Save aungthuoo/e6404fda5cb375670335010fffcb53d4 to your computer and use it in GitHub Desktop.
Node.js basic routing without using express.js

Node.js basic routing

const http = require("http");

var routes = {
  "/": function index(request, response) {
    response.writeHead(200);
    response.end("Hello, World!");
  },
  "/foo": function foo(request, response) {
    response.writeHead(200);
    response.end('You are now viewing "foo"');
  },
};

function index(request, response) {
  response.writeHead(200);
  response.end("Hello, World!");
}
http
  .createServer(function (request, response) {
    /*
    if (request.url === "/") {
      return index(request, response);
    }
    response.writeHead(404);
    response.end(http.STATUS_CODES[404]);
    */

    if (request.url in routes) {
      return routes[request.url](request, response);
    }
    response.writeHead(404);
    response.end(http.STATUS_CODES[404]);
  })
  .listen(1337);

Testing :

http://127.0.0.1:1337/
http://127.0.0.1:1337/foo

Output :

Hello, World!
You are now viewing "foo"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment