MangoDB+Express+AngularJS+NodeJS搭建待辦任務管理系統(一)

NodeJS:搭建Web服務器

Express4:搭建Restfull服務

MongoDB:作爲數據庫

mongoose組件:連接MongoDB

AngularJS+Bootstrap+Foundation:UI界面

IntelliJ:開發工具


1、準備工作

安裝好Nodejs,NPM,MongoDB,Express


2、項目搭建

Step 1:選擇一個可以在裏面創建項目的文件夾,在文件夾上利用Git Bash打開命令窗口,輸入:

express MyTodo

此時,項目文件夾以及其中的基本文件已經創建,再輸入:

cd MyTodo && npm install

此時,項目相關的依賴包已經安裝。

利用Git Bash,輸入:npm start,即會出現:


在瀏覽器中輸入:http://localhost:3000/

就會出現:Welcome to Express

--------------------------------------------------------------------------------------------------------------

step 2:如果不習慣使用ejs,可以將ejs換爲html,方法如下:

找到app.js,將其中的

app.set('view engine', 'jade');

換爲

app.engine('.html', require('ejs').renderFile);
app.set('view engine', 'html');
然後,將views文件夾下的ejs文件改爲html文件。

再次輸入:npm start,在瀏覽器查看。

因爲每次修改文件都要重新啓動web 服務,可以採用 nodemon 讓它幫我們自動更新,輸入:

npm install nodemon -g

然後,輸入:nodemon,即可不再需要每次改動都npm start了。

--------------------------------------------------------------------------------------------------------------

step 3:安裝MongoDB驅動mongoose,輸入:

npm install mongoose --save

然後將mongoose加入到MyTodo/app.js中:


然後你會發現:

[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node ./bin/www`
connection succesful

--------------------------------------------------------------------------------------------------------------

step 4:創建models文件夾,在其中新建Todo.js

 mkdir models

 touch models/Todo.js

在Todo.js中寫入:


--------------------------------------------------------------------------------------------------------------

step 5:利用AngularJS的$http或者$resource與RESTful APIs進行交互

在routes文件夾下新建todos.js,

在app.js中加入todos路由:

var todos = require('./routes/todos');
app.use('/todos', todos);

在todos.js中寫入:

var express = require('express');
var router = express.Router();

var mongoose = require('mongoose');
var Todo = require('../models/Todo.js');

/* GET todos listing. */
router.get('/', function (req, res, next) {
    Todo.find(function (err, todos) {
        if (err) return next(err);
        res.json(todos);
    });
});

module.exports = router;
然後在瀏覽器中查看:http://localhost:3000/todos

即可看到:[ ]

--------------------------------------------------------------------------------------------------------------

step 6:繼續在routes/todos.js中加入其它數據庫操作方法:


可以使用Google插件postman進行測試,至此,後端搭建已經完成。

--------------------------------------------------------------------------------------------------------------

step 7:搭建前端

將routes/index.js中的title值改爲myTodo App

在views/index.html中添加如下代碼:

<ng-view></ng-view>

<!-- Libraries -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-resource.min.js"></script>

<!-- Template -->
<script type="text/ng-template" id="/todos.html">
    Search:<input type="text" ng-model="search.name">
    <ul>
        <li ng-repeat="todo in todos | filter:search">
            <input type="checkbox" ng-model="todo.completed" ng-change="update($index)">
            <a ng-show="!editing[$index]" href="#/{{todo._id}}">{{todo.name}}</a>
            <button ng-show="!editing[$index]" ng-click="edit($index)">Edit</button>
            <button ng-show="!editing[$index]" ng-click="remove($index)">Remove</button>

            <input ng-show="editing[$index]" type="text" ng-model="todo.name">
            <button ng-show="editing[$index]" ng-click="update($index)">Update</button>
            <button ng-show="editing[$index]" ng-click="cancel($index)">Cancel</button>
        </li>
    </ul>

    New task <input type="text" ng-model="newTodo">
    <button ng-click="save()">Create</button>
</script>

<script type="text/ng-template" id="/todoDetails.html">
    <h1>{{todo.name}}</h1>
    completed: <input type="checkbox" ng-model="todo.completed"><br>
    note: <textarea ng-model="todo.note"></textarea><br><br>

    <button ng-click="update()">Update</button>
    <button ng-click="remove()">Remove</button>
    <a href="/">Cancel</a>
</script>

<script>
    angular.module('app', ['ngRoute', 'ngResource'])

    //---------------
    // Services
    //---------------
            .factory('Todos', ['$resource', function ($resource) {
                return $resource('/todos/:id', null, {
                    'update': {method: 'PUT'}
                });
            }])

            //---------------
            // Controllers
            //---------------

            .controller('TodoController', ['$scope', 'Todos', function ($scope, Todos) {
                $scope.editing = [];
                $scope.todos = Todos.query();

                $scope.save = function () {
                    if (!$scope.newTodo || $scope.newTodo.length < 1) return;
                    var todo = new Todos({name: $scope.newTodo, completed: false});

                    todo.$save(function () {
                        $scope.todos.push(todo);
                        $scope.newTodo = '';//clear textbox
                    })
                }

                $scope.update = function (index) {
                    var todo = $scope.todos[index];
                    Todos.update({id: todo._id}, todo);
                    $scope.editing[index] = false;
                }

                $scope.edit = function (index) {
                    $scope.editing[index] = angular.copy($scope.todos[index]);
                }

                $scope.cancel = function (index) {
                    $scope.todos[index] = angular.copy($scope.editing[index]);
                    $scope.editing[index] = false;
                }

                $scope.remove = function (index) {
                    var todo = $scope.todos[index];
                    Todos.remove({id: todo._id}, function () {
                        $scope.todos.splice(index, 1);
                    })
                }
            }])

            .controller('TodoDetailCtrl', ['$scope', '$routeParams', 'Todos', '$location', function ($scope, $routeParams, Todos, $location) {
                $scope.todo = Todos.get({id: $routeParams.id});
                $scope.update = function () {
                    Todos.update({id: $scope.todo._id}, $scope.todo, function () {
                        $location.url('/');
                    });
                }

                $scope.remove = function () {
                    Todos.remove({id: $scope.todo._id}, function () {
                        $location.url('/');
                    });
                }
            }])

            //---------------
            // Routes
            //---------------

            .config(['$routeProvider', function ($routeProvider) {
                $routeProvider
                        .when('/', {
                            templateUrl: '/todos.html',
                            controller: 'TodoController'
                        })

                        .when('/:id', {
                            templateUrl: '/todoDetails.html',
                            controller: 'TodoDetailCtrl'
                        });
            }]);
</script>
在瀏覽器中即可看到如下視圖:


如果需要換端口,可以採用如下方式:

PORT=4000 nodemon


OK,基本項目建設完畢,接下來將進行框架的文件整理,後面將繼續更新~~~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章