http://www.jdon.com/45599 banq
分如下步骤:
1> Angular.js 用于客户端开发,目前只用一个页面作为案例
2> 跨网络领域联系是Angular.js和 Node.js
3> Node.js用于服务器端开发
4> 使用express.js创建REST服务
5> Database – MongoDb
6> Node.js MongoDb Module Extention (mongojs)
架构图如下:

具体步骤:
下载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); |
继续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 + '"},' +'\n';
});
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 server app.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.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服务取得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> |

本文介绍如何使用Angular.js进行客户端开发并与Node.js集成,通过Express.js创建REST服务,利用MongoDB进行数据存储。同时提供了前后端代码实现示例。
230

被折叠的 条评论
为什么被折叠?



