Node JS Tutorial - Simple Routing
In this tutorial, we will learn about simple routing in Node.js. Routing defines how client requests are handled by application endpoints, allowing users to load different URLs in their browser.
Each different URL represents a different route. Let's see how we can set up basic Node.js routes.
Step 1: Create HTML Files
Go to your project and create three new HTML files: home.html, about.html, and contact.html.
Step 2: Add Content to HTML Files
Open the home.html file and add the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
</head>
<body>
<h1>Home Page</h1>
</body>
</html>
Next, open the about.html file and add the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HoAboutme</title>
</head>
<body>
<h1>About Page</h1>
</body>
</html>
Finally, open the contact.html file and add the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact</title>
</head>
<body>
<h1>Contact Page</h1>
</body>
</html>
Step 3: Create a Server with Routing
Open the index.js file and require the http module. Then, add the following code:
var http = require('http');
var server = http.createServer(function(req,res)
{
if(req.url === '/home' || req.url === '/')
{
res.writeHead(200,{'Content-Type':'text/html'});
res.createReadStream(__dirname + '/home.html')pipe(res);
}
else if(req.url === '/about')
{
res.writeHead(200,{'Content-Type':'text/html'});
res.createReadStream(__dirname + '/about.html')pipe(res);
}
else if(req.url === '/contact')
{
res.writeHead(200,{'Content-Type':'text/html'});
res.createReadStream(__dirname + '/about.html')pipe(res);
}
else.
{
res.writeHead(404,{'Content-Type':'text/html'});
res.createReadStream(__dirname + '/about.html')pipe(res);
}
});
Step 4: Test the Routes
Go to the command prompt and run the index.js file:
node index.js
Switch to your browser and refresh the page. You should see the home page. If you navigate to /about, you will see the about page. Similarly, if you navigate to /contact, you will see the contact page.
That's it! You have successfully created simple routes using Node.js. This is a fundamental concept in web development, and is used extensively in web applications.