Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Node.js Creating Server With Routes

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 875
    Comment on it

    Node.js is a javascript based platform built in Chrome's javascript V8 engine. Creating web server in Node is easy. Node.js is light weight and fast performance It handle great number of simultaneous request at a same time. Node come with some fantastic build in module used to setup your own http server. The http module is used to create server that will listen to a port.

    Create a server

    Creating server using node http module and listen to port.

    var http = require('http');
    http.createServer(function(request, response) {
    	response.end('App is running ' + request.url);
    }).listen(3003, function() {
    	console.log('Server running on port 3003');
    });

    First install http module using npm.

    npm install http

    Then run the code using node.

    node fileName.js

    Look for http://localhost:3003.

    Adding route to http server

    After creating the http server now let's add some routes to app. The http-dispatcher module will help you to achieve this functionality by using less efforts. In the below code snippet the dispatcher module will be used with http server taht we created in above code.

    var http = require('http');
    var dispatcher = require('httpdispatcher');
    
    //Set url using http dispatcher
    dispatcher.setStatic('public');
    dispatcher.setStaticDirname('.');
    dispatcher.onGet('/', function(request, response) {
    	response.end('This is home page');
    });
    dispatcher.onGet('/about', function(request, response) {
    	response.end('This is about page');
    });
    dispatcher.onError(function(request, response) {
    	response.writeHead(404);
    	response.end('Page not found.!');
    });
    
    http.createServer(function(request, response) {
    	dispatcher.dispatch(request, response);
    }).listen(3003, function() {
    	console.log('Server running on port 3003');
    });

    First install http and httpdispatcher using npm command.

    npm install http
    npm install httpdispatcher

    Then run the code using node.

    node fileName.js

    View on browser using http://localhost:3003.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: