使用 Angular.js, Node.js 和 MongoDB开发简单案例

分如下步骤:
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>

Single Page Application with Angular.js, Node.js and MongoDB (MongoJS Module)

[该贴被admin于2016-04-05 17:08修改过]

banq老师最近很关注angular.js啊。。。

2013-07-19 11:18 "@lostalien
"的内容
banq老师最近很关注angular.js ...

是的,angular.js的前端MVC实现很优雅,可伸缩性Scalable又很好,完全可替代以前后端表现层框架如Struts SpringMVC等等,后端只要领域层+薄的JSON格式REST层即可,更无需JSF那么重量。

未来主流架构应该是:

前端浏览器:angular.js等MVC框架
后端: REST+ CQRS

总结为: MVC+REST+CQRS

为什么要使用MVC+REST+CQRS
J2EE死了 javacript + 后端JSON服务方式胜出 :http://www.jdon.com/44690
[该贴被banq于2013-07-20 16:14修改过]

赞成 banq 老师的这种观点。

angular.js 等 + REST+ CQRS

1、充分分离的前端和后端,交互之需要借助JSON。
2、后端完全看作是服务提供者。

交互交给最接近用户的那一层去做,复杂的东西交于后端的云去做。


刚搜了下,像这种js的mvc,目前还有几个,比如backbone.js,knockout.js啥的,为啥选择angular.js呢?

Node.js这个技术主要使用的场景是什么呢?现在这个技术成熟了么?刚刚看到板桥老师说以后后端是: Node.js java ESB,node.js 跟java是不是有点重复了呢?

周末看了看angularjs,的确很不错,用它做 单页面应用舒服多了,当然,用extjs,dojo这些也可以做单页面应用。

这个例子我怎么运行不起来呢?
执行:node appmongodbangular.js
在浏览器地址录入:http://localhost:1212/client/angular/angularnodeuser.html

显示Cannot GET /client/angular/angularnodeuser.html

怎么回事? 有谁能帮帮我? 谢谢!

看不到目录结构,目录结构的图挂了...小白好无力,.