Node.js tutorial: how to use the routes

In this tutorial I will speak about the Node.js's routes. I will show you the easiest way to create and use the routes in Node.js.

First I will create a simple server:

var router = require("./router.js");

var http = require("http");

var server = http.createServer(function(request,response)
{

});

server.listen(300,"localhost");

In the createServer function, I will add:

router.homepage(request,response);
router.about(request,response);

to execute two routes.

Next, I will create the file router.js with two routes:

function homepage(request,response)
{
if(request.url === "/")
{
response.writeHead(200,{"Content-Type":"text/html"});
response.write("
<h2>Hello World!</h2>
");
response.end();
}
}

function about(request,response)
{
if(request.url === "/about")
{
response.writeHead(200,{"Content-Type":"text/html"});
response.write("
<h2>About me Page!</h2>
");
response.end();
}
}

module.exports.homepage = homepage;

module.exports.about = about;

I have created also a video tutorial:









Leave a Comment

How to use HTML templates in Node.js - Scrisoft Tutorials
How to use HTML templates in Node.js - Scrisoft Tutorials commented on June 24, 2015
[…] In this tutorial I will explain how to use HTML templates in pure Node.js without express. I will work with the files from my last tutorial about Node.js. […]