Tuesday, May 19, 2015

Node JS with Express

In this post I will explain how to create a node js web application using express js.
First create a Visual Studio Node JS project using following way.
The project structure would look like this.
You have to install express as a npm package. There are several ways to do that.

  • Using npm package manager
  • Edit package.json file and install npm packages via command line
  • Using command line directly install and save the version to package.json

My preference is last one.
To organize our project in much readable way, we will use MVC pattern. Most important thing we should remember is, we have to use MVC pattern in both in server and client side code. Therefore we must have proper naming conventions for files. Add MVC folders according to following structure.
Add student.server.controller.js file into controllers folder. The code should be like below. In here I used common js module pattern.
Next we need to create routes for the student.server.controller. Add routes folder and add student.server.route.js file into that. First you have to load controller dependency. Routing module function accept single argument called app, where we need to pass instance of Express application. Withing the function we should configure router path with related route method to call.
Now we can configure express middleware in a proper way. To do that, add config folder and add express.js file into that folder.
Content of the express.js file should like below. In the configuration method, it loads the route and pass express instance to that.
Final step is to configure server.js file.
Run the app using node server command.
Browse for http://localhost:3000/ . You will see following result.
In a next post I will show how to render the student list in a proper way.

No comments:

Post a Comment