Skip to content

Latest commit

 

History

History
57 lines (46 loc) · 1.08 KB

section1.6.md

File metadata and controls

57 lines (46 loc) · 1.08 KB

Section 1.6: Hello World basic routing

const http = require('http');

/**** 1st way ****/
function index (req, res) {
  res.writeHead(200);
  res.end('Hello, World!');
}

http.createServer(function (req, res) {
  if (req.url === '/') {
    return index(req, res);
  }
    res.writeHead(404);
    res.end(http.STATUS_CODES[404]);

}).listen(3040);
/**** 2nd way ****/
let 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"');
  }
}

http.createServer(function (request, response) {
  if (request.url in routes) {
    return routes[request.url](request, response);
  }

  response.writeHead(404);
  response.end(http.STATUS_CODES[404]);
}).listen(3050);