How to Create Routing in Node.js

in #utopian-io7 years ago (edited)

nodejs-new-pantone-white.png
image-sources :https://nodejs.org/static/images/logo.svg

This tutorial we will see what the user input in our url and we will give response to user which page will be loaded. in the website must be the user will interact with our web, one of them through routing. and I will make the routing system in nodejs simply.

Create Routes.js

We will create a file with route.js name as our routing source.


var url  = require('url');
var fs   = require('fs');
function renderFile(url, response){
    response.writeHead(200,{'Content-Type': 'text/html'});
    fs.readFile(url,null,function(error,data){
        if(error){
            response.writeHead(400);
            response.write("File not Found!")
        }else{
            response.write(data)
        }
    });
}
module.exports = {
    handleRequest: function(request,response){
        response.writeHead(200,{'Content-Type': 'text/html'});
        var path = url.parse(request.url).pathname;
        switch (path){
            case '/':
            renderFile('./index.html',response)
            break;
            case '/profil':
            renderFile('./profil.html',response)
            break;
            case '/about':
            renderFile('./about.html',response)
            break;
        default:
        }
    }
};

var url = require ( ' url ' ) : we imported the module to read our web url, Its automatically comes by itself when you install node js
var fs = require( ' fs ' ) : we imported the module to read our web url,Its automatically comes by itself when you install node js. function readFile( url, response ) { } : we create a function that will serve to render the file. in the render file we accept the url parameter, and the response. url is the parameter we get from the browser url. response.writeHead( 200, { ' Content-Type ' : ' text/htm l' } ) : we will put code 200 means succeed and no problem. then we give { ' Content-Type ' : ' text/html ' } because this file has html. fs.readFile( ' ./index.html ' ,null,function( error,data ) { } : we read the file with readFile . we read file index.html , we can add options in second parameter, but in this tutorial we pass null, cause we dont pass anything.
module.exports = { } 

we will export a module, named handleRequest, before if you are not familiar with export module. that means we can export function or also variable in File A to File B or File B to File A var path = url.parse( request.url ).pathname : we will catch what the user input in our url, here we save it on the variable path. we use the module that we have imported var url = require ( 'url' )
switch (path){
            case '/':
            renderFile('./index.html',response)
            break;
            case '/profil':
            renderFile('./profil.html',response)
            break;
            case '/about':
            renderFile( './about.html',response )
            break;
        default:
        }

We will make the switch operator to determine which files will be rendered with the function renderFile ( ' ./nameFile.html ' , response ) .

Create Server.js

Now we will make the server to render the file, in this tutorial I created server.js .


var http    = require('http');
var route   = require('./route');
http.createServer(route.handleRequest).listen(3000,function(){
    console.log("listening on port 3000")
});

var http = require( ' http ' ) : Http is a module that automatically comes by itself when you install node js. This module is used to connect about the server.
var route = require( ' ./route ' ) : we will import the module from the route.js.route is just variable name.


http.createServer(route.handleRequest).listen(3000,function(){
    console.log("listening on port 3000")
});

This is our way to create a server with the function createServer ( ) , and then we will passing data from the module route we have imported from route.js, the function we will use from the route module is handleRequest , so to access the function to be like this route.handleRequest and we listen in the server port localhost:3000

Results the Routing

We have 3 simple files to make example.
1 . index.html for path '/'
Screenshot_6.png

2 . profil.html for path '/profil'
Screenshot_7.png
3 . about.html for path '/about'
Screenshot_8.png

Done, we have made basic routing in node js. purpose of this tutorial so we understand how the routing pattern is in node.js, and remember we make it all pure with javascript language. So many of me hopefully this tutorial useful to you



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Hey @alfarisi94 I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x