Getting start with Express: creating a HTTP server with express Js

Express is a minimal and flexible Node.js web application framework. It's the most popular framework as of now (the most starred on NPM). So Express make easy writing node.js programs.

First of all you should have node.js installed.

Here is how a simple HTTP server can be implemented with Express.

Initial setup

First Express should be installed globally and locally with NPM. If you have installed express ignore these two steps.

  1. Install Express globally with NPM(Node Package Manager)
    npm install -g express
  2. Install express locally
    npm install express
    npm install express --save if you using a package.json file to track your project
Lets get in to code,
  1. Require "Express" package in our Application
    var express = require('express');
  2. Create an Express object
    var app = express();
  3. Create routing
    
    app.get('/',function(req,res){  
    
        res.send('Hello Express');
    
    });
    Here we pass expected URL pattern('/') and required functionality as a function to express method get()
  4. Creating a server with a listening port
    
    var server = app.listen(3000,function(){
    
        console.log('Listening on port 3000');
    
    });
  5. Run your server with node fileName.js and try it with a browser

Here is the complete code for that server

var express = require('express'); //importing the express library

 var app = express();   //create an express object

//routing
app.get('/',function(req,res){  
    res.send('Hello Express');
});

//create a server
var server = app.listen(3000,function(){
    console.log('Listening on port 3000');
});




No comments:

Post a Comment