mongo + express + ng2 + nodejs tasklist

准备

  1. nodejs

  2. mongo

目录

|-client
    |-app
        |-components
            |-task
                |-tasks.component.html
                |-tasks.components.ts
            |-services
                |-task.services.ts
            |-app.component.html
            |-app.component.ts
            |-app.module.ts
            |-main.ts
        |-bower_components
        |-node_modules
        |-typings
        |-package.json
        |-systemjs.config.js
        |-Task.ts
        |-tsconfig.json
        |-typings.json
    |-node_modules
    |-routes
        |-index.js
        |-tasks.js
    |-views
        |-index.html
    |-.bowerrc
    |-package.json
    |-server.js

开始

后端

  1. cd tasklist && npm init #创建项目

  2. npm install mongojs express ejs body-parser –save

  3. touch server.js

    var express = require('express')
    var path = require('path')
    var bodyParser = require('body-parser')

    var index = require('./routes/index');
    var tasks = require('./routes/tasks');

    var port = 3000;
    var app = express();

    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'ejs');
    app.engine('html', require('ejs').renderFile);

    app.use(express.static(path.join(__dirname, 'client')));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: false}));


    app.use('/', index);
    app.use('/api', tasks);

    app.listen(port, function () {
        console.log('Server started on port' + port)
    });
  1. mkdir routes && cd routes

  2. touch index.js

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

    router.get('/', function (req, res, next) {
        res.render('index.html');
    });
    module.exports = router;
  1. mkdir views && cd views && touch index.html

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        HELLO WORLD
    </body>
</html>
  1. touch tasks.js

var express = require('express')
var router = express.Router();
var mongojs = require('mongojs')
var db = mongojs('mongodb://localhost:27017/nodeapp', ['tasks'])

router.get('/tasks', function (req, res, next) {
    db.tasks.find(function (err, tasks) {
        if (err) {
            res.send(err);
        }
        res.json(tasks);
    });
});

router.get('/task/:id', function (req, res, next) {
    db.tasks.findOne({_id: mongojs.ObjectId(req.params.id)}, function (err, task) {
        if (err) {
            res.send(err);
        }
        res.json(task);
    })
});

router.post('/task', function (req, res, next) {
    var task = req.body;
    if (!task.title || !(task.isDone + '')) {
        req.status(400);
        res.json({
            "error": 'Bad Date'
        });
    } else {
        db.tasks.save(task, function (err, task) {
            if (err) {
                res.send(err);
            }
            res.json(task);
        });
    }
});

router.delete('/task/:id', function (req, res, next) {
    db.tasks.remove({_id: mongojs.ObjectId(req.params.id)}, function (err, task) {
        if (err) {
            res.send(err);
        }
        res.json(task);
    })
})

router.put('/task/:id', function (req, res, next) {
    var task = req.body;
    var updTask = {};

    if (task.isDone) {
        updTask.isDone = task.isDone;
    }
    if (task.title) {
        updTask.title = task.title;
    }
    if(!updTask) {
        res.status(400);
        res.json({
            "error": 'Bad Data'
        })
    } else {
        db.tasks.update({_id: mongojs.ObjectId(req.params.id)}, updTask, function (err, task) {
            if (err) {
                res.send(err);
            }
            res.json(task);
        });
    }
})

module.exports = router;

前端

  1. mkdir client && mkdir app

  2. touch package.json

{
  "name": "angular-quickstart",
  "version": "1.0.0",
  "scripts": {
    "start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
    "lite": "lite-server",
    "postinstall": "typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "typings": "typings"
  },
  "licenses": [
    {
      "type": "MIT",
      "url": "https://github.com/angular/angular.io/blob/master/LICENSE"
    }
  ],
  "dependencies": {
    "@angular/common": "~2.1.0",
    "@angular/compiler": "~2.1.0",
    "@angular/core": "~2.1.0",
    "@angular/forms": "~2.1.0",
    "@angular/http": "~2.1.0",
    "@angular/platform-browser": "~2.1.0",
    "@angular/platform-browser-dynamic": "~2.1.0",
    "@angular/router": "~3.1.0",
    "@angular/upgrade": "~2.1.0",
    "angular-in-memory-web-api": "~0.1.5",
    "bootstrap": "^3.3.7",
    "core-js": "^2.4.1",
    "reflect-metadata": "^0.1.8",
    "rxjs": "5.0.0-beta.12",
    "systemjs": "0.19.39",
    "zone.js": "^0.6.25"
  },
  "devDependencies": {
    "concurrently": "^3.0.0",
    "lite-server": "^2.2.2",
    "typescript": "^2.0.3",
    "typings":"^1.4.0"
  }
}
  1. touch typings.json

{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160725163759",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160909174046"
  }
}
  1. touch tsconfig.json

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": false
    }
}
  1. systemjs.config.js

/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',
      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      // other libraries
      'rxjs':                      'npm:rxjs',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      },
      'angular-in-memory-web-api': {
        main: './index.js',
        defaultExtension: 'js'
      }
    }
  });
})(this);
  1. npm install

  2. touch .bowerrc

{
  "directory": "./client/bower_components"
}
  1. bower install bootstrap –save

Demo

    原文作者:yuluhuang
    原文地址: https://segmentfault.com/a/1190000007254280
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞