您的位置:首页 > 数据库 > Mongodb

REST架构网站改写:前端MVC - Angular.js,Web框架 - Express.js, 数据库 - MongoDB

2013-01-11 11:37 871 查看
  Coenraets分享了自己开发的一个Single Page Restful网站(http://coenraets.org/blog/2012/10/nodecellar-sample-application-with-backbone-js-twitter-bootstrap-node-js-express-and-mongodb)。

  他利用多种不同的前后端技术改写了这个项目,大致有以下这些:

  CSS库 - Bootstrap;

  前端MVC - Backbone.js,Angular.js;

  Web框架 - Express.js(Node.js)、PHP、Java ;

  数据库 - MongoDB、MySQL。

  其中,我最感兴趣Angular + Express + MongoDB的组合,Coenraets恰好没有实现;再加之Angular新版本改进颇大,尤其是Coenraets的实现没有使用angular.modular,所以我做了些改写,核心代码如下。

  Express Server部分:监听和响应客户端HTTP请求。

app.get('/wines', wine.findAll);
app.get('/wines/:id', wine.findById); //retrieve
app.post('/wines', wine.addWine);  //create
app.put('/wines/:id', wine.updateWine);  //update
app.delete('/wines/:id', wine.deleteWine);  //delete


  前端MVC架构:响应用户请求,完成大部分UI逻辑

  controller.js

angular.module('controller', ['service']).
config(function($routeProvider) {
$routeProvider.when('/wines', {templateUrl:'tpl/welcome.html'}).
when('/addWine',{templateUrl:'tpl/wine-details.html', controller:AddWineCtrl}).
when('/wines/:wineId', {templateUrl:'tpl/wine-details.html', controller:WineDetailCtrl}).
otherwise({redirectTo:'/wines'});
});

function WineListCtrl($scope, Wine) {
Wine.query(function(wines) {
$scope.wines = wines;
});
}

function AddWineCtrl($scope, $location,  Wine) {
// POST /wines
$scope.saveWine = function() {
Wine.save($scope.wine, function() {
$location.path("/wines");
});
};
}

function WineDetailCtrl($scope, $location, $routeParams, Wine) {

// GET /wines/id
Wine.get({wineId: $routeParams.wineId}, function(wine){
$scope.wine = wine;
});

// PUT /wines/id
$scope.saveWine = function () {
Wine.update({wineId: $routeParams.wineId},
$scope.wine, function() {
$location.path("/wines");
});
};

//DELETE /wines/id
$scope.deleteWine = function () {
Wine.delete({wineId: $routeParams.wineId}, function() {
$location.path("/wines");
});
};
}


  service.js

angular.module('service', ['ngResource']).
factory('Wine', function($resource) {
return $resource('/wines/:wineId', {}, {
update: {method:'PUT'}
});
});


  整个项目前后端完全隔离,通过Restful协议通信;Express框架在Node.js中的地位类似于Django之于Python或Rails之于Ruby,新版Myspace是利用它开发的;Angular.js能大幅度减轻前端MVC工作量,直接进行DOM操纵而无需jQuery。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: