In this blog, you will learn to build a single-page application with Angular.js, Node.js, and MongoDB. The following are the technologies that we need to build this single-page application.
Use Angular.js for client-side development to develop Single Page App
Communication between Angular.js and Node.js for Cross-Domain Communication
Node.js use for server-side development
Creating web service with express.js based on Rest
Database- MongoDB
Node.js MongoDB Module Extention (mongojs)
Prerequisite
Command npm install mongojs
Command npm install express
Step 1: Configuration Code
We will describe the code here:
var application_root = __dirname, express = require("express"), path = require("path"); |
Use javascript variables to initialize the express.js in respect of Node.js concept.
The above code shows the initialization of the web server in the application variable.
var databaseUrl = "sampledb"; var collections = ["things"] var db = require("mongojs").connect(databaseUrl, collections); |
Here you can connect mongodb database with the help of Node.js mongojs module extension library.
// Config app.configure(function () { app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(application_root, "public"))); app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); |
Here we have configured to express.js
Step 2: Rest Services Code
app.get('/api', function (req, res) { res.send('Our Sample API is up...'); }); |
We have tested the REST-based web services and tested the code whether express.js.
app.get('/getangularusers', function (req, res) { res.header("Access-Control-Allow-Origin", "http://localhost"); res.header("Access-Control-Allow-Methods", "GET, POST"); // The above 2 lines are required for Cross Domain Communication(Allowing the methods that come as Cross // Domain Request db.things.find('', function(err, users) { // Query in MongoDB via Mongo JS Module if( err || !users) console.log("No users found"); else { res.writeHead(200, {'Content-Type': 'application/json'}); // Sending data via json str='['; users.forEach( function(user) { str = str + '{ "name" : "' + user.username + '"},' +'\n'; }); str = str.trim(); str = str.substring(0,str.length-1); str = str + ']'; res.end( str); // Prepared the jSon Array here } }); }); |
To obtain all usernames from the user collection, we have made another REST API call and supplied the mongojs query.
app.post('/insertangularmongouser', function (req, res){ console.log("POST: "); res.header("Access-Control-Allow-Origin", "http://localhost"); res.header("Access-Control-Allow-Methods", "GET, POST"); // The above 2 lines are required for Cross Domain Communication(Allowing the methods that come as // Cross Domain Request console.log(req.body); console.log(req.body.mydata); var jsonData = JSON.parse(req.body.mydata); db.things.save({email: jsonData.email, password: jsonData.password, username: jsonData.username}, function(err, saved) { // Query in MongoDB via Mongo JS Module if( err || !saved ) res.end( "User not saved"); else res.end( "User saved"); }); }); |
Here, we've used REST calling to make a POST request to create a user.
Step 3: Angular.js part
The following code in Angular Controller:
'use strict'; var myApp = angular.module('myApp', []); // Taking Angular Application in Javascript Variable // Below is the code to allow cross domain request from web server through angular.js myApp.config(['$httpProvider', function($httpProvider) { $httpProvider.defaults.useXDomain = true; delete $httpProvider.defaults.headers.common['X-Requested-With']; } ]); /* Controllers */ function UserListCtrl($scope, $http, $templateCache) { var method = 'POST'; var inserturl = 'http://localhost:1212/insertangularmongouser';// URL where the Node.js server is running $scope.codeStatus = ""; $scope.save = function() { // Preparing the Json Data from the Angular Model to send in the Server. var formData = { 'username' : this.username, 'password' : this.password, 'email' : this.email }; this.username = ''; this.password = ''; this.email = ''; var jdata = 'mydata='+JSON.stringify(formData); // The data is to be string. $http({ // Accessing the Angular $http Service to send data via REST Communication to Node Server. method: method, url: inserturl, data: jdata , headers: {'Content-Type': 'application/x-www-form-urlencoded'}, cache: $templateCache }). success(function(response) { console.log("success"); // Getting Success Response in Callback $scope.codeStatus = response.data; console.log($scope.codeStatus); }). error(function(response) { console.log("error"); // Getting Error Response in Callback $scope.codeStatus = response || "Request failed"; console.log($scope.codeStatus); }); $scope.list();// Calling the list function in Angular Controller to show all current data in HTML return false; }; $scope.list = function() { var url = 'http://localhost:1212/getangularusers';// URL where the Node.js server is running $http.get(url).success(function(data) { $scope.users = data; }); // Accessing the Angular $http Service to get data via REST Communication from Node Server }; $scope.list(); } |
Step 4: Angular Template and HTML
<html lang="en" ng-app="myApp"> ..... |
We’ve talked about the Angular app in the above code.
<body ng-controller="UserListCtrl"> ..... |
In the code above, we referenced the Angular Controller.
Search: <input ng-model="user"> <div class="span10"> <!--Body content--> <ul class="users"> <li ng-repeat="user in users | filter:user "> {{user.name}} </li> </ul> </div> |
We have taken the users' data model through REST communication and displayed it in HTML using the ng-repeat tag.
<form name="myform" id="myform1" ng-submit="save()"> <fieldset> <legend>New User</legend> <div class="control-group"> <center><input type="text" placeholder="User…" ng-model="username" size=50 required/></center> <center><input type="text" placeholder="Password…" ng-model="password" size=50 required/></center> <center><input type="text" placeholder="Email…" ng-model="email" size=50 required/></center> </div> </fieldset> <p> <div><center><button type="submit" >Save now...</button></center></div> </p> </form> |
The user data model was delivered from REST connection to the node server to be saved in MongoDB using the ng-submit tag.
No comments:
Post a Comment