使用Nodejs+Express和MongoDB实现TodoList

首先讲解步骤

1、建立一个文件夹:命名为:express-todolist

其中包含文件夹:controllers、public、views

为了先安装我们项目中要用到的工具和扩展内容

我们讲鼠标的光标放在编辑区域,单击定位后,按下鼠标上的:Ctrl+Alt+o打开编译区,

输入命令

npm install express --save //安装express插件  得到文件夹node_modules

输入命令

npm install mongoose ejs nodemon --svae  //安装mongoose数据库插件、ejs模板引擎、nodemon保存编译的插件

之后可以输入命令

npm init  //初始化我们的环境,然后输出文件package-lock.json和package.json


以及文件:app.js

使用Nodejs+Express和MongoDB实现TodoList_第1张图片

其中有:

app.js

var express = require("express");

var todoController = require('./controllers/todoController');
//让app使用express()方法
var app = express();

//使用模板引擎
app.set('view engine', 'ejs');

todoController(app);
//调用静态方法
app.use(express.static("./public"));

app.get('/', function(req, res) {
    res.send("this is the home page!");
    console.log("home page!")
});


//监听3000端口
app.listen(3000);
console.log("you are listening to port 3000");

todoController.js

var bodyParser = require("body-parser");
var urlencodeParser = bodyParser.urlencoded({extended: false });
var mongoose = require("mongoose");
mongoose.connect('mongodb://Lin_fairy:[email protected]:11309/todo_test');
// 模板
var todoSchema = new mongoose.Schema({
    item: String
});
//模型
var Todo = mongoose.model("Todo", todoSchema);

// var itemOne = Todo({item: "buy book"}).save(function(err) {
//     if(err) throw err;
//     console.log()
// });

// var data = [{item:"get milk"},{item:"wolk dog"},{item:"kick some coding"}];

module.exports = function (app) {
    app.get('/todo', function(req, res) {
        Todo.find({}, function(err, data) {
            if(err) throw err;
            res.render('todo', {todos: data});
        });
    });

    app.post('/todo', urlencodeParser, function(req, res) {
        var itemOne = Todo(req.body).save(function(err, data) {
            if(err) throw err;
            res.json(data);
        });
        
    });

    app.delete('/todo/:item', function(req, res) {
        // data = data.filter(function(todo) {
        //     return todo.item.replace(/ /g, '-') !== req.params.item;
        // });
        //存在一个问题,如果有两条数据是一样的,将会删除掉所有相同的数据
        Todo.find({item: req.params.item.replace(/-/g, " ")}).remove(function(err, data) {
            if(err) throw err;
            res.json("data");
        });
    });
}

styles.css

body {
    background: #0d1521;
    font-family: tahoma;
    color: #989898;
}

#todo-table {
    position: relative;
    width: 95%;
    background: #090d13;
    margin: 0 auto;
    padding: 20px;
    box-sizing: border-box;
}

#todo-table form:after {
    margin: 0;
    content: '';
    display: block;
    clear: both;
}

input[type="text"] {
    width: 30%;
    padding: 20px;
    background: #181c22;
    border: 0;
    float: left;
    font-size: 20px;
    color: #989898;
}

button {
    padding: 20px;
    width: 30%;
    float: left;
    background: #23282e;
    border: 0;
    box-sizing: border-box;
    color: #fff;
    cursor: pointer;
    font-size: 20px;
}

ul {
    list-style-type: none;
    padding: 0;
    margin: 0;
}

li {
    width: 100%;
    padding: 20px;
    box-sizing: border-box;
    font-family: arial;
    font-size: 20px;
    cursor: pointer;
    letter-spacing: 1px;
}

li:hover {
    text-decoration: line-through;
    background: rgba(0, 0, 0, 0.2);
}

todo-list.js

$(document).ready(function() {

    $('form').on('submit', function(event) {
        event.preventDefault();
        var item = $('form input');
        var todo = { item: item.val().trim() };

        $.ajax({
            type: 'POST',
            url: '/todo',
            data: todo,
            success: function(data) {
                //do something with the data via front-end framework
                location.reload();
            }
        });

        return false;

    });

    $('li').on('click', function() {
        var item = $(this).text().trim().replace(/ /g, "-");
        $.ajax({
            type: 'DELETE',
            url: '/todo/' + item,
            success: function(data) {
                //do something with the data via front-end framework
                location.reload();
            }
        });
    });

});

todo.ejs




    
    
    
    
    Todo List
    
    


    
    <% todos.forEach(function(todo) { %>
  • <%= todo.item %>
  • <% }) %>


你可能感兴趣的:(使用Nodejs+Express和MongoDB实现TodoList)