Search This Blog

2015-12-05

Express

Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It allows to set up middlewares to respond to HTTP  Requests and defines a routing table which is used to perform different action based on HTTP Method and URL.It allows to dynamically render HTML Pages based on passing arguments to templates.


To Install Mean Stack run the following comment
  • npm install -g mean-cli
and make the initial structure of the project by following command
  • mean init yourNewApp
or, Run below command to install only the Express
  • npm install express --save                 
There are following important modules which you should install along with express:
  • body-parser - This is a node.js middleware for handling JSON, Raw, Text and URL encoded form data.
  • cookie-parser - Parse Cookie header and populate req.cookies with an object keyed by the cookie names.
  • multer - This is a node.js middleware for handling multipart/form-data.


  • $ npm install body-parser --save
  • $ npm install cookie-parser --save
  • $ npm install multer --save


Step 1: Run "npm init"

Step 2 : Insert all required parameter in 'npm init' and create the start page 'index.js'.

Step 3:Amend the package.json as below

{
  "name": "demoforexpress",
  "version": "1.0.0",
  "description": "Demo for Express",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "MRB",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.14.1",
    "cookie-parser": "^1.4.0",
    "express": "^4.13.3",
    "multer": "^1.1.0"
  }
}

Step 4: index.js will be as below

var express = require('express');
var app = express();
app.get('/', function (req, res) {
 console.log("Get method Called")
   res.send('Response from GET method');
})
// This responds a POST request for the homepage
app.post('/', function (req, res) {
   console.log("Post method called");
   res.send('Response from POST method');
})
// This responds a DELETE request for the /del_user page.
app.delete('/del_user', function (req, res) {
   console.log("delete method called for /del_user");
   res.send('Response from Delete Method');
})
// This responds a GET request for the /list_user page.
app.get('/list_user', function (req, res) {
   console.log("get Method called for /list_user");
   res.send('response from GET for /list_user');
})
// This responds a GET request for abcd, abxcd, ab123cd, and so on
app.get('/ab*cd', function(req, res) {  
   console.log("Got a GET request for /ab*cd");
   res.send('Response from Page Pattern Match');
})
var server = app.listen(8081, function () {
  var host = server.address().address
  var port = server.address().port
  console.log("Example app listening at http://%s:%s", host, port)
})




Step 5: Run the application by 'node index.js' , test in rest client and see the responses in console.

----------------------------More on Express-------------------------------------
package.json

{
  "name": "demoforexpress",
  "version": "1.0.0",
  "description": "Demo for Express",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "MRB",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.14.1",
    "cookie-parser": "^1.4.0",
    "express": "^4.13.3",
    "multer": "^1.1.0",
    "express-session":"*",
    "connect-busboy":"*",
    "path":"*",
    "fs-extra":"*",
    "formidable":"*"
  }
}

index.js

// fsutil file createnew index.js 2000
var express = require('express');
var app = express();
///-------------Basic Authentication-----------------------
var loginuser;
// Authenticator
app.use(function(req, res, next) {
    var auth;
   
    // check whether an autorization header was send   
    if (req.headers.authorization) {
      // only accepting basic auth, so:
      // * cut the starting "Basic " from the header
      // * decode the base64 encoded username:password
      // * split the string at the colon
      // -> should result in an array
      auth = new Buffer(req.headers.authorization.substring(6), 'base64').toString().split(':');
  
    }
    // checks if:
    // * auth array exists
    // * first value matches the expected user
    // * second value the expected password
    if ((!auth || auth[0] !== 'testuser' || auth[1] !== 'testpassword') && (!auth || auth[0] !== 'testuser2' || auth[1] !== 'testpassword2'))
    {
        // any of the tests failed
        // send an Basic Auth request (HTTP Code: 401 Unauthorized)
        res.statusCode = 401;
        // MyRealmName can be changed to anything, will be prompted to the user
        res.setHeader('WWW-Authenticate', 'Basic realm="MyRealmName"');
        // this will displayed in the browser when authorization is cancelled
        res.end('Unauthorized');
    } else {
        // continue with processing, user was authenticated
        loginuser=auth[0];
        next();
    }
    // if (!auth || auth[0] !== 'testuser' || auth[1] !== 'testpassword')
    // {
    //     // any of the tests failed
    //     // send an Basic Auth request (HTTP Code: 401 Unauthorized)
    //     res.statusCode = 401;
    //     // MyRealmName can be changed to anything, will be prompted to the user
    //     res.setHeader('WWW-Authenticate', 'Basic realm="MyRealmName"');
    //     // this will displayed in the browser when authorization is cancelled
    //     res.end('Unauthorized');
    // } else {
    //     // continue with processing, user was authenticated
    //     loginuser=auth[0];
    //     next();
    // }
});

////------------------------------End Authentication-------------------------------
app.get('/', function (req, res) {
 console.log("Get method Called")
   res.send('Response from GET method');
})
// This responds a POST request for the homepage
app.post('/', function (req, res) {
   console.log("Post method called");
   res.send('Response from POST method');
})
// This responds a DELETE request for the /del_user page.
app.delete('/del_user', function (req, res) {
   console.log("delete method called for /del_user");
   res.send('Response from Delete Method');
})
// This responds a GET request for the /list_user page.
app.get('/list_user', function (req, res) {
   console.log("get Method called for /list_user");
   res.send('response from GET for /list_user');
})
// This responds a GET request for abcd, abxcd, ab123cd, and so on
app.get('/ab*cd', function(req, res) {  
   console.log("Got a GET request for /ab*cd");
   res.send('Response from Page Pattern Match');
})
//------------------Cookie---------------------------
//This responds a GET request for cookie
var cookieParser = require('cookie-parser');
app.use(cookieParser());
app.get('/cookie', function (req, res) {
  //res.clearCookie("mycookie");
  res.cookie("mycookie","manab",{maxAge:864000000});
  res.setHeader('Content-Type', 'text/plain');
  res.send('Response from GET Cookie method ' +JSON.stringify(req.cookies));
})
//------------------Session---------------------------
//This responds a GET request for session
var session = require('express-session');
app.use(cookieParser());
app.use(session({ secret: 'loginuser', cookie: { maxAge: 60000 }}));
app.get('/session', function (req, res) {
var sess = req.session;
if (sess.views) {
    sess.views++
    res.setHeader('Content-Type', 'text/html')
    res.write('views: ' + sess.views + '
')
    res.write('expires in: ' + (sess.cookie.maxAge / 1000) + 's
')
    res.end()
  } else {
    sess.views = 1
    res.end('welcome to the session demo. refresh!')
  }
})
//------------------Uploading File---------------------------
//HTML For Uploading File
/*<!DOCTYPE html>
<html lang="en" ng-app="APP">
<head>
    <meta charset="UTF-8">
    <title>angular file upload</title>
</head>
<body>
        <form method='post' action='upload' enctype="multipart/form-data">
        <input type='file' name='fileUploaded'>
        <input type='submit'>
 </body>
</html>*/


var busboy = require('connect-busboy'); //middleware for form/file upload
var path = require('path');     //used for file path
var fs = require('fs-extra');       //File System - for file manipulation
app.use(busboy());
app.use(express.static(path.join(__dirname, 'public')));
//------------Without formidable--------
// app.route('/upload')
//     .post(function (req, res, next) {
//         var fstream;
//         req.pipe(req.busboy);
//         req.busboy.on('file', function (fieldname, file, filename) {
//             console.log("Uploading: " + filename);
//             //Path where image will be uploaded
//             fstream = fs.createWriteStream(__dirname + '/img/' + filename);
//             file.pipe(fstream);
//             fstream.on('close', function () {   
//                 console.log("Upload Finished of " + filename);             
//                 res.redirect('back');           //where to go next
//             });
//         });
//     });
//--------------------------------------
//------------------Uploading File With formidable
var bodyParser=require("body-parser");
var formidable = require("formidable");
app.use(bodyParser({defer: true}));
 app.route('/upload')
 .post(function (req, res, next) {
  var form = new formidable.IncomingForm();
    //Formidable uploads to operating systems tmp dir by default
    form.uploadDir = "./img";       //set upload directory
    form.keepExtensions = true;     //keep file extension
    form.parse(req, function(err, fields, files) {
        res.writeHead(200, {'content-type': 'text/plain'});
        res.write('received upload:\n\n');
        console.log("form.bytesReceived");
        //TESTING
        console.log("file size: "+JSON.stringify(files.fileUploaded.size));
        console.log("file path: "+JSON.stringify(files.fileUploaded.path));
        console.log("file name: "+JSON.stringify(files.fileUploaded.name));
        console.log("file type: "+JSON.stringify(files.fileUploaded.type));
        console.log("astModifiedDate: "+JSON.stringify(files.fileUploaded.lastModifiedDate));
        //Formidable changes the name of the uploaded file
        //Rename the file to its original name
        fs.rename(files.fileUploaded.path, './img/'+files.fileUploaded.name, function(err) {
        if (err)
            throw err;
          console.log('renamed complete'); 
        });
          res.end();
    });
});

//----------------------------------------------------
var server = app.listen(8081, function () {
  var host = server.address().address
  var port = server.address().port
  console.log("Example app listening at http://%d:%d", host, port)
})

Create server using HTTP,Express and HAPI

HTTP:
var http=require('http');
var handlerMethod=function(req,res){
 res.end("Hello, This is a message from the handler of web server of");
}
http.createServer(handlerMethod).listen(1234,'localhost');
console.log("Http Server is running");

Express:
var express = require('express');
var app = express();
app.get(*,function(req,res){
 res.end("response from server");
});
var server = app.listen(3000, function(){
    console.log('Listening on port %d', server.address().port);
});

Hapi:
var Hapi = require('hapi');
var server = new Hapi.Server(3000);//port number during initialize
server.start(function () {
    console.log('Server running at:', server.info.uri);
});

Difference between req.params,req.query and req.body :

(req.params) Checks route params, ex: /user/:id
(req.query) Checks query string params, ex: ?id=12 Checks urlencoded body params
(req.body), ex: id=12 To utilize urlencoded request bodies, req.body should be an object. This can be done by using the _express.bodyParser middleware.

Use Basic Authentication in the above example from Adv Rest Client:
URL-http://localhost:8081/
Header would be -Authorization: Basic dGVzdHVzZXI6dGVzdHBhc3N3b3Jk
To change the Authorization,Click on Form ->'Edit Value' for authorization header->Basic

Difference between res.end and res.send :
res.send('Response from POST method');-automatically assumes a Content-Type of html
res.end('Response from POST method');-so no assumptions are made for the Content-Type

Send cookie in response in the above example
use- cookie-parser to set and get cookie in request and response
call -http://localhost:8081/cookie to check also the request cookie which is firsttime set by response cookie


Output - Response from GET Cookie method {"_ga":"GA1.1.2097241217.1451846328","mycookie":"manab"}

Use Session Variable in the above example:
call http://localhost:8081/session from different type of browser , IE+Chrome
Delete Moudles which is can't be deleted for alonger file path name
npm install rimraf -g
rimraf node_modules

Upload file:
ref:http://stackoverflow.com/questions/23691194/node-express-file-upload
node index.js and open http://localhost:8081/index.html
Two example , first one is commented and without formidable , second one with formidable package

No comments: