分如下步驟:
1> Angular.js 用于客戶端開發(fā),目前只用一個頁面作為案例
2> 跨網(wǎng)絡(luò)領(lǐng)域聯(lián)系是Angular.js和 Node.js
3> Node.js用于服務(wù)器端開發(fā)
4> 使用express.js創(chuàng)建REST服務(wù)
5> Database – MongoDb
6> Node.js MongoDb Module Extention (mongojs)
架構(gòu)圖如下:
具體步驟:
下載Node.js,然后安裝mongojs和express
npm install mongojs
npm install express
配置:
var application_root = __dirname, express = require("express"), path = require("path");
//使用express var app = express();
|
連接MongoDB:
var databaseUrl = "sampledb"; var collections = ["things"] var db = require("mongojs").connect(databaseUrl, collections);
|
繼續(xù)express配置:
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 })); });
|
REST服務(wù)代碼:
app.get('/api', function (req, res) { res.send('Our Sample API is up...'); });
|
好了,我們已經(jīng)準(zhǔn)備了后端代碼,REST服務(wù)在:
http://127.0.0.1:1212/api
(GET方法)
下面是REST服務(wù) http://127.0.0.1:1212/getangularusers (Get Method)
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 } }); });
|
下面是REST服務(wù)POST代碼:http://127.0.0.1:1212/insertangularmongouser(Post Method)
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"); }); });
|
啟動服務(wù)器:
// Launch server app.listen(1212);
|
在命令行啟動
node appmongodbangular.js
至此服務(wù)器后端全部完成。
下面是前端Angular.js部分,控制器代碼
'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(); }
|
Angular Template and HTML
<html lang="en" ng-app="myApp"> <body ng-controller="UserListCtrl">
//用ng-repeat從REST服務(wù)取得users的數(shù)據(jù)模型 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>
//用ng-submit將user數(shù)據(jù)模型提交給后端,保存到MongoDB <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>
|
Single Page Application with Angular.js, Node.js and MongoDB (MongoJS Module)
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請
點(diǎn)擊舉報。