美文网首页
MEAN开发指南

MEAN开发指南

作者: babybus_hentai | 来源:发表于2016-04-08 14:19 被阅读241次

    MEAN栈包含数个用于开发Web应用的JavaScript技术。MEAN是MongoDBExpressAngularJSNode.js的首字母缩写词。从浏览器端到数据库,MEAN全都是JavaScript。我们接下来对MEAN一探究竟,并使用它来创建一个心愿清单程序。

    <h2 id="step_1">简介</h2>
    Node.js是一种JavaScript在服务端的运行环境。它基于Google Chrome的V8(一种JavaScript运行时)。非常适合用来构建灵活的、高并发的应用。

    Express,一种轻巧的框架,使用Node创建Web应用。它提供了很多健壮的特性用于构建单页或者多页的Web应用。Express受到了Sinatra的影响,后者是一种流行的Ruby框架。

    MongoDB是一种无范式的NoSQL数据库。MongoDB使用二进制的JSON格式来存储数据,方便客户端和服务端之间的数据传递。

    AngularJS是Google开发的一个JavaScript框架。它提供了一些非常赞的特性,比如数据的双向绑定。它是完整的快省的前端开发解决方案。

    在本文中,我们将使用MEAN创建一个CRUD的应用。继续深入。
    <h2 id="step_2">准备</h2>
    在开始之前,你需要安装几个MEAN用到的包。从安装Node.js开始,到下载页去下载。接下来,下载并安装MongoDB。在MongoDB的安装教程中包含了在各种系统中搭起Mongo的方法。为了简化过程,我们从一个MEAN的模板项目开始。直接将这个模板项目clone下来,使用npm安装依赖即可。命令如下:

    git clone http://github.com/linnovate/mean.git
    cd mean
    npm install
    

    安装好了必要的包,接下来,按照模板中README中说的,设置默认端口27017,MongoDB泡在这个端口上。打开文件/etc/mongodb.conf,取消掉 port = 27017这行的注释。好了,使用下面的命令重启mongod服务器。

    mongod --config /etc/mongodb.conf
    

    接下来,在项目的根目录下运行grunt,没什么问题的话,你将会看到这条消息:

    Express app started on port 3000 
    

    服务器已经起来了,在浏览器中访问http://localhost:3000/,查看运行中模板项目。

    <h2 id="step_3">项目模板概览</h2>

    现在我们已经有了一个功能完整的模板项目了。包括用户认证功能,可以使用社交账号登录。我们不会往这个方向深入下去,就开始写我们自己的小应用了。如果你一定要知道的话,那就是AngularJS之类的前端代码放在public文件夹中,而NodeJS后端代码则放在server这个文件夹中。

    <h2 id="step_4">创建一个列表视图</h2>

    我们从使用AngularJS来构建我们的前端开始。进入public文件夹,新建名为bucketList的文件夹,我们把前端文件放到这里。在bucketList中,创建子文件夹controllers、routes、services和views。同时创建一个名为bucketList.js文件,添加如下代码:

    'use strict';
    
    angular.module('mean.bucketList', []);
    

    接下来,打开mean/public/init.js,添加模块mean.bucketList,添加后如下面这样:

    angular.module('mean', ['ngCookies', 'ngResource', 'ui.bootstrap', 'ui.router', 'mean.system', 'mean.articles', 'mean.auth', 'mean.bucketList']);
    

    现在到 public/bucketList/routes目录中添加路由文件bucketList.js,用来处理应用的路由。添加如下的代码就可以实现:

    'use strict';
    //Setting up route
    angular.module('mean.bucketList').config(['$stateProvider', '$urlRouterProvider',
      function($stateProvider, $urlRouterProvider) {
        // states for my app
        $stateProvider
          .state('all bucket list', {
            url: '/bucketList',
            templateUrl: 'public/bucketList/views/list.html'
          });
      }
    ]);
    

    在public/bucketList/views/创建list.html,我们的视图层,用来显示列表。文件中添加如下代码:

    <section data-ng-controller="BucketListController">
      Welcome to the bucket list collection
    </section>
    

    还要在public/bucketList/controllers创建一个bucketList.js:

    'use strict';
     
    angular.module('mean.bucketList').controller('BucketListController', ['$scope', '$stateParams', '$location', 'Global',
      function($scope, $stateParams, $location, Global) {
        $scope.global = Global;
      }
    
    ]);
    

    接下来,grunt启动应用。要确定MonoDB已经跑起来了。访问http://localhost:3000/#!/bucketList, 应该可以看到我们创建的列表视图。URL中的#!是为了把AngularJS和NodeJS各自的路由隔开。

    <h2 id="step_5">向列表中添加内容</h2>

    创建一个新视图,用来向列表里添加内容。在public/bucketList/views添加新文件create.html,添加代码如下:

    <section data-ng-controller="BucketListController">
      <form class="form-horizontal col-md-6" role="form" data-ng-submit="create()">
        <div class="form-group">
          <label for="title" class="col-md-2 control-label">Title</label>
          <div class="col-md-10">
            <input type="text" class="form-control" data-ng-model="title" id="title" placeholder="Title" required>
          </div>
        </div>
        <div class="form-group">
          <label for="description" class="col-md-2 control-label">Description</label>
          <div class="col-md-10">
            <textarea data-ng-model="description" id="description" cols="30" rows="10" placeholder="Description" class="form-control" required></textarea>
          </div>
        </div>
        <div class="form-group">
          <div class="col-md-offset-2 col-md-10">
            <button type="submit" class="btn btn-default">Submit</button>
          </div>
        </div>
      </form>
    
    </section>
    

    这段代码绑定了控制器BucketListController。注意表单提交的地方,调用了create()方法。接下来,我们在这个控制器中创建一个名为create()方法。向public/bucketList/controllers/bucketList.js中添加如下代码。如代码所示,我们向控制器中注入了BucketList服务,用来与服务端交互。

    'use strict';
     
    angular.module('mean.bucketList').controller('BucketListController', ['$scope', '$stateParams', '$location', 'Global', 'BucketList',
      function ($scope, $stateParams, $location, Global, BucketList) {
        $scope.global = Global;
     
        $scope.create = function() {
          var bucketList = new BucketList({
            title: this.title,
            description: this.description
          });
     
          bucketList.$save(function(response) {
            $location.path('/bucketList');
          });
        };
      }
    ]);
    

    public/bucketList/services/bucketList.js中的如下:

    'use strict';
     
    angular.module('mean.bucketList').factory('BucketList', ['$resource',
      function($resource) {
        return $resource('bucketList);
      }
    ]);
    

    我们还需要添加一个新的路由,用来添加条目到列表。修改public/bucketList/routes/bucketList.js,添加一个新的状态:

    'use strict';
     
    //Setting up route
    angular.module('mean.bucketList').config(['$stateProvider', '$urlRouterProvider',
      function($stateProvider, $urlRouterProvider) {
        // states for my app
        $stateProvider
          .state('all bucket list', {
            url: '/bucketList',
            templateUrl: 'public/bucketList/views/list.html'
          })
          .state('add bucket list', {
            url: '/addBucketList',
            templateUrl: 'public/bucketList/views/create.html'
          })
      }
    ]);
    

    重启服务,访问http://localhost:3000/#!/addBucketList,你应该会看到创建条目的表单,不过它还不能工作,我们还需要提供后端服务。提供后端服务
    列表条目包含title、description和status字段。所有创建server/models/bucketlist.js,添加如下代码:

    'use strict';
     
    /**
     * Module dependencies.
     */
    var mongoose = require('mongoose'),
      Schema = mongoose.Schema;
     
    /**
     * Bucket List Schema
     */
    var BucketListSchema = new Schema({
      created: {
        type: Date,
        default: Date.now
      },
      title: {
        type: String,
        default: '',
        trim: true
      },
      description: {
        type: String,
        default: '',
        trim: true
      },
      status: {
        type: Boolean,
        default: false
      }
    });
     
    mongoose.model('BucketList', BucketListSchema);
    

    我们需要配置Express的路由,为AngularJS的调用提供服务。创建server/routes/bucketList.js,添加代码:

    'use strict';
     
    var bucketList = require('../controllers/bucketList');
     
    module.exports = function (app) {
      app.post('/bucketList', bucketList.create);
    };
    

    bucketList.create()处理发送到/bucketList的POST请求。这个方法由服务器端的控制器提供——bucketList.js,这个文件还未创建,创建它,添加如下内容:

    'use strict';
     
    /**
     * Module dependencies.
     */
    var mongoose = require('mongoose'),
      BucketList = mongoose.model('BucketList');
     
    /**
     * Create an Bucket List
     */
    exports.create = function(req, res) {
      var bucketList = new BucketList(req.body);
     
      bucketList.save(function(err) {
        if (err) {
          console.log(err);
        } else {
          res.jsonp(bucketList);
        }
      });
    };
    

    代码还有很多可以改进的地方,不过让我先看看它是否能够工作。当用户提交了AngularJS表单,调用AngularJS服务,接着就会调用服务器端的create方法,最终把数据插入到MongoDB中。

    在提交表单之后,我们可以检查数据是否正确地插入到了Mongo中,要查看MongoDB中的数据,打开一个新的控制台,输入如下命令:

    mongo                   // Enter the MongoDB shell prompt
    show dbs;               // Shows the existing Dbs
    use mean-dev;           // Selects the Db mean-dev
    show collections;       // Show the existing collections in mean-dev
    db.bucketlists.find()   //Show the contents of bucketlists collection
    

    <h2 id="step_6">创建愿望清单视图</h2>

    首先在server/routes/bucketList.js添加一个新的路由:

    app.get('/bucketList', bucketList.all);
    

    这个路由调用控制器的all()方法。如下给server/controllers/bucketList.js添加这个方法,从bucketList集合中查找条目并返回:

    exports.all = function(req, res) {
      BucketList.find().exec(function(err, bucketList) {
        if (err) {
          console.log(err);
        } else {
          res.jsonp(bucketList);
        }
      });
    
    };
    

    接下来,在public/bucketList/controllers/bucketList.js添加:

    $scope.getAllBucketList = function() {
      BucketList.query(function(bucketList) {
        $scope.bucketList = bucketList;
      });
    };
    

    这段代码从Mongo中获取数据,将其保存到$scope.bucketList中。现在,我们只需要把它和我们的HTML绑定在一起就可以了。在public/bucketList/views/list.html添加如下代码实现:

    <section data-ng-controller="BucketListController" data-ng-init="getAllBucketList()">
      <ul class="bucketList unstyled">
        <li data-ng-repeat="item in bucketList">
          <span>{{item.created | date:'medium'}}</span> /
          <span>{{item.title}}</span>
     
          <div>{{item.description}}</div>
        </li>
      </ul>
      <a href="/#!/addBucketList">Create One</a>
    </section>
    

    重启服务器,访问http://localhost:3000/#!/bucketList,愿望清单应该显示出来的吧。你可以点击列表下的”Create”来创建新的条目。

    <h2 id="step_7">总结</h2>

    本文中,我们把注意力放在使用MEAN技术栈创建一个简单的应用上。我们实现了向MongoDB中添加数据,并从中读取显示出来。如果你有兴趣继续扩展这个例子,你可以尝试提供更新和删除操作。文本涉及到的代码可以在Github上找到。

    相关文章

      网友评论

          本文标题:MEAN开发指南

          本文链接:https://www.haomeiwen.com/subject/rxuvlttx.html