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
You can also use new extension quick install in visual studio 2015 for installing express or jade
once you installation is done then your solution structure looks as below
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
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
open the App.js file all the module dependencies are loaded to respective variables
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
calling a particular route can be written as below
creating a server for listening the requests
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
Run the application then you will see the following output
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.
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
establish the connection to the mongodb as shown below
use connect method to connect to the database
As everything is collection in mongo db world , we have created a simple sports_data collection and printed on console
the same data can be returned to view in node express. stay tune for rendering the data from apis to view in node express.