Techbubbles

What is Node Express?

Node Express is a minimal, open source and flexible node.js web app framework designed to develop websites, web apps and APIs much easier. Especially developing single page applications is easy with node express. This post outlines the node express features , creating a simple REST API and interacting with Mongo database to get the data and show on  views.

Why should I use Node Express?

Express helps you to respond to the requests with route support, you can respond to requests and write specific responses to specific URLs. It also supports multiple templating engines to simplify generating HTML.templating is like reusing your html again and again. Jade is out of the box templating engine in Node with strong focus on performance and powerful features.

Installing and Using Node Express

   1: npm install express

   2: npm install jade

You can also use new extension quick install in visual studio 2015 for installing express or jade

image

once you installation is done then your solution structure looks as below

image

you will also see there is stylus node package in solution, which is nodejs based css pre-processor. Stylus CSS files will have .styl extension and can be placed anywhere in your project. it compiles and generates a css output. example shown below

image

Creating a simple REST API with express is easy, if you create a node express 3 project in Visual Studio 2015 then it will add all the code that required for writing the simple REST API for you

 

image

open the App.js file all the module dependencies are loaded to respective variables

   1: /**

   2:  * Module dependencies.

   3:  */

   4:  

   5: var express = require('express');

   6: var routes = require('./routes');

   7: var user = require('./routes/user');

   8: var http = require('http');

   9: var path = require('path');

to call the functions on express assign to as below

var app = express();

setting the environments, specifying the view engine and using the routes can be done as below

   1: // all environments

   2: app.set('port', process.env.PORT || 3000);

   3: app.set('views', path.join(__dirname, 'views'));

   4: app.set('view engine', 'jade');

   5: app.use(express.favicon());

   6: app.use(express.logger('dev'));

   7: app.use(express.json());

   8: app.use(express.urlencoded());

   9: app.use(express.methodOverride());

  10: app.use(app.router);

  11: app.use(require('stylus').middleware(path.join(__dirname, 'public')));

  12: app.use(express.static(path.join(__dirname, 'public')));

calling a particular route can be written as below

   1: app.get('/', routes.index);

   2: app.get('/users', user.list);

creating a server for listening the requests

   1: http.createServer(app).listen(app.get('port'), function () {

   2:     console.log('Express server listening on port ' + app.get('port'));

   3: });

when you run the application it first goes to route index.js and it will send the html response to view index.jade. folder structure and their content looks as below

image

image

Run the application then you will see the following output

image

MongoDB can be installed using npm install mongodb, MongoDB database organization is different from relational database. each database in mongo contains collections and each collection you store the documents in json format. for example, each collection can be collection of places or collection of BLOG posts.

image

you can also download mongodb as global by downloading the msi from here. once you install the mongodb , navigate to the folder that you have installed and type mongod to start the mongodb

image

establish the connection to the mongodb as shown below

   1: //import the language driver

   2: var MongoClient = require('mongodb').MongoClient;

   3: var assert = require('assert');

   4: var ObjectID = require('mongodb').ObjectID;

   5: //Connection URL for local mongodb server

   6: var url = 'mongodb://127.0.0.1:27017/test';

use connect method to connect to the database

   1: MongoClient.connect(url, function (err, db) {

   2:     //ensure we've connected

   3:     assert.equal(null, err);

   4:  

   5:     var sportsData = db.collection('sports_data');

   6:  

   7:     sportsData.insertOne({

   8:         name: "Football",

   9:         players: "11",

  10:  

  11:     }, function (err, op_result) {

  12:  

  13:         if (err) {

  14:             return console.error(err);

  15:         }

  16:  

  17:         console.log('inserted:');

  18:         console.log(op_result.ops[0]);

  19:  

  20:  

  21:     });

  22:     return console.log("Connected correctly to server");

  23: });

As everything is collection in mongo db world , we have created a simple sports_data collection and printed on console

image

the same data can be returned to view in node express. stay tune for rendering the data from apis to view in node express.

Related Posts:

%d bloggers like this: