By Daniel Du
As a web programmer starting from the traditional ASP/ASP.net, sometimes my mind was constricted to the old days. My understanding of web application was how asp.net works, the HTML is generated at server side, and send it to browser to render. One guy asked me how to display some data which retrieved from server during a hackathon, while I am just in the middle of something, my distinctive response is to ask him to do something like <%= something%>, like ASP/ASP.NET does. But nowadays, it has been changed a lot, we have very different architecture – RESTful, which separates the server side and client side completely, and it also makes it easy for the server to serve different clients, including browsers and mobile devices.
Here is an architecture graph I “steal” from strongloop. As you can see, with RESTful architecture, the web server exposes some REST APIs, the client communicates with the server with REST call. This make it very flexible, the client can be a browser as a common website, it also can be mobile device like iPhone/iPad or Android phone or pad. For the browser, you can user different libraries or frameworks to build your UI, you can use JQuery, Angular.Js or anything else you like.
Let’s make a simplest sample to demo the idea, a web server with Node.Js + Express, and a browser client with Angular.Js. The idea is to make a todo list. Firstly I will create a simplest web server with Node.Js and Express. The express CLI make it really easy. If you do not have express installed, install it first with help of google. And then create a simplest express web application with express generator:
mkdir simpleWebApp
cd simpleWebApp
npm install
This will create a simplest web application with node.js and express, if you run “npm start” and go to “http://localhost:3000” you will see the first welcome page of express.
Now let’s do some simple work to add a REST API:
GET /todos - Get all todo items
Before that, we will add some test data in JSON, in practice, you will get these todo items from a database like MongoDb. For simplicity, we make it a JSON file named as “todoItems.json”
[ { "task": "buy milk", "complete":false }, { "task": "toast bread", "complete":false }, { "task": "pick up newspaper", "complete":false }, { "task": "water flowers", "complete":false } ]
Then go to /routes/index.js, add a new route, response all todo items in json:
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res) { res.render('index', { title: 'Express' }); }); var sampleToDoItems = require('../todoTasks.json'); /* GET Todo listing. */ //GET /Todos/ router.get('/todos', function(req, res) { res.type('application/json'); res.status(200); res.json(sampleToDoItems); }); module.exports = router;
Now, the REST API is ready, if I start the web application, and go to postman with GET http://localhost:3000/todos, or go to the url in browser directly, I will get all todo items:
The server side is done, next we will do the client side. We will use Angular.JS. Actually the client does not have to be in the same project of web server, but for simplicity, I put it together. The express has already setup the structure, the /public folder contains the static contents. I create a webpage named as “index.html” in it, and then I edit “route/index.js” file to change the route so that when I go to “http://localhost:3000/” it goes to my index.html page:
/* GET home page. */ router.get('/', function(req, res) { //res.render('index', { title: 'Express' }); res.redirect('/index.html'); });
Let’s do the angular part, in “index.html” to include the angular js library, and create our angular module and controller. It is very simple one, so I put them into a single JS file. The idea is just to send a GET request to the web server and get all todo items, the import part is to inject the $http into the controller:
var app = angular.module('myTodoApp',[]); app.controller('myTodoCtrl', function($scope, $http){ $http.get('/todos') .success(function(response){ $scope.todoItems = response; }); });
And then go to the “index.html” page, I put the important port in bold so that it is easy to follow. Firstly we need an “ng-app”, otherwise angular.Js will not run. And then put the “ng-controller” to the table, and build the table with ng-repeat="todo in todoItems", please note that the “todoItems” is populated in controller by http get request, they are completed in client side already:
$scope.todoItems = response;
The the databind can be done by “ng-bind” or “{{ something }}”. Here is the complete code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title Page</title> <!-- Bootstrap CSS --> <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <h1 class="text-center">Hello World</h1> <div class="container" ng-app="myTodoApp"> <table class="table table-striped table-hover" ng-controller="myTodoCtrl"> <thead> <tr> <th></th> </tr> </thead> <tbody> <tr ng-repeat="todo in todoItems"> <td>{{todo.task}}</td> <td><div class="checkbox"> <label> <input type="checkbox" value="" ng-model="todo.complete"> </label> </div></td> </tr> </tbody> </table> </div> <!-- jQuery --> <script src="//code.jquery.com/jquery.js"></script> <!-- Bootstrap JavaScript --> <script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> <script src="//www.runoob.com/try/angularjs/1.2.5/angular.min.js"></script> <script src="/javascripts/myTodoApp.js"></script> </body> </html>
And this is how it looks like when running the app:
OK, that’s the idea, very simple, of cause in practical, if will be more complex, and you can user various frameworks, like mean.io, cleverstack, sail.js.
Comments
You can follow this conversation by subscribing to the comment feed for this post.