使用 Angular.js, Node.js 和 MongoDB開發簡單案例

分如下步驟:1> Angular.js 用於客戶端開發,目前只用一個頁面作為案例2> 跨網路領域聯繫是Angular.js和 Node.js3> Node.js用於伺服器端開發4> 使用express.js創建REST服務5> Database – MongoDb6> Node.js MongoDb Module Extention (mongojs)架構圖如下:

具體步驟:下載Node.js,然後安裝mongojs和expressnpm install mongojsnpm 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);

繼續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服務代碼:

app.get("/api", function (req, res) { res.send("Our Sample API is up...");});

好了,我們已經準備了後端代碼,REST服務在:http://127.0.0.1:1212/api(GET方法)下面是REST服務 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 + ""}," +"
"; }); str = str.trim(); str = str.substring(0,str.length-1); str = str + "]"; res.end( str); // Prepared the jSon Array here } });});

下面是REST服務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"); });});

啟動伺服器:

// Launch serverapp.listen(1212);

在命令行啟動node appmongodbangular.js至此伺服器後端全部完成。下面是前端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.jsmyApp.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服務取得users的數據模型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數據模型提交給後端,保存到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)
推薦閱讀:

這兩款籃子裝包包,簡單實用,織一個送給自己吧~
荊門人聚餐常吃的7種家常風味小炒肉,做起來真的好簡單!
【圖】編織教程圖解 簡單的紅繩編織戒指教程_圖老師
麵條這樣做好吃又過癮,大人小孩搶著吃,連吃三天,簡單好學
生活本來簡單快樂,別折騰了!

TAG:Node.js | MongoDB | 案例 | 簡單 | Angular |