Express JS is flexible NODE.JS web application framework that provides a robust set of features to develop mobile and web applications.
It also facilitates the rapid development of Node based Web Applications.
Features of Express JS
- Allows setting up of middle-ware to respond to HTTP Requests.
- Defines a routing table which is used to perform different actions based on HTTP Method and URL
Pre-Requisites
1. Node JS
2. MS SQL Database (for demo - any database can be used)
Step-1
Step 1: Create a package.json file.
{
"name": "<Application Name>",//e.g. – node_app
"version": "0.0.0",
"description": "<Description about your application>",
"main": "server.js",
"dependencies": {
"express": "4.14.0",
"body-parser": "1.15.2",
"mssql":"3.3.0"
},
"scripts": {
"start": "node server.js"
},
"author": {
"name": "<Your Name>",
"email": "<Your Email>"
}
}
Step-2
Step 2: Create server.js file.
//Initiallising node modules
var express = require("express");
var bodyParser = require("body-parser");
var sql = require("mssql");
var app = express();
// Setting Base directory
app.use(bodyParser.json());
//CORS Middleware
app.use(function (req, res, next) {
//Enabling CORS
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, contentType,Content-Type, Accept, Authorization");
next();
});
//Setting up server
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
//Initiallising connection string
var dbConfig = {
user: "<username>",
password: "<password>",
server: "<severName>",
database: "<database",
port: "<port>",
requestTimeout: '10000',
debug: true,
dialect: "mssql",
options: {
encrypt: true // Use this if you're on Windows Azure
}
};
var pool = function(){
var conn = new sql.Connection(dbConfig, function(err){
var request = new sql.Request(conn);
//console.dir(request);
return request;
});
return conn;
}
//Function to connect to database and execute query
var executeQuery = function(res, query){
var dbConn = new sql.Connection(dbConfig);
dbConn.connect().then(function () {
var request = new sql.Request(dbConn);
request.query(query).then(function (recordSet) {
//console.log(recordSet);
res.send(recordSet);
dbConn.close();
}).catch(function (err) {
console.log(err);
dbConn.close();
});
}).catch(function (err) {
console.log(err);
});
}
app.get("/api/dpc", function(req , res){
var query = "select count(*) as count from [schema].[table]";
executeQuery(res,query);
});
Step -3
npm install
Step-4
node server.js
The node server will start running into port number 8080 with corresponding API Routes; you can point to the below URL to test the application.