<repo_name>skammm/node-express<file_sep>/03/03-用mongodb重构crud/02-crud-express/router.js

/**
 * 路由映射表
 * get  /student
  get  /student/add
  post /student/add
  get  /student/edit
  post  /student/edit
  get   /student/delete
 * 
 
 */

var express = require('express');
var router = express.Router();
var fs = require('fs');
var student = require('./student.js')
var image=['/public/img/x1.jpg','/public/img/x2.jpg','/public/img/x3.jpg','/public/img/x4.jpg']

router.get('/student', function (req, res) {
  student.find(function(err,data){
    if(err){
      return res.send(err)
    }
    res.render('index.html',{
      image:image,
      students:data
    })
  })
  
})

router.get('/student/add', function (req, res) {
  res.render('add.html',{
    image:image
  })
})

router.post('/student/add', function (req, res) {
  new student(req.body).save(function(err){
    if(err){
      return handleError(err);
    }
    res.redirect('/student');
  })
})


router.get('/student/edit', function (req, res) {
  student.findById(req.query.id,function(err,data){
    if(err){
      return res.send(err);
    }
    res.render('edit.html',{
      student:data,
    })
  })
})


router.post('/student/edit', function (req, res) {
  student.findOneAndUpdate(req.body.id,req.body,function(err){
    if(err){
      return res.send(err);
    }
    res.redirect('/student')
  })
})


router.get('/student/delete', function (req, res) {
  var del = {};
  del.id = req.body.id
  student.findOneAndRemove(del,function(err){
    if(err){
      return res.send(err)
    }
    res.redirect('/student')
  })
})

module.exports = router;<file_sep>/03/02-crud-express/student.js
/**
 * 用来完成对json文件的增删改查，处理数据逻辑
 */



/*
  获取所有学生列表
*/
var path = './db.json';
var fs = require('fs')
exports.find = function(callback){
  fs.readFile(path,function(err,data){
    if(err){
      return callback(err)
    }
    callback(null,JSON.parse(data.toString()).students)
  })
}
/**
 * 获取某个学生的个人信息
 * @param {Number} id
 * @param {Function} callback
 */
exports.findById = function(id,callback){
  fs.readFile(path,function(err,data){
    if(err){
      return callback(err)
    }
    var students = JSON.parse(data.toString()).students;
    var student = students.find(item=>{
      return item.id == parseInt(id);
    })
    callback(null,student);
  })
}

/*
  添加学生信息
*/
exports.add = function(student,callback){
  fs.readFile(path,function(err,data){
    if(err){
      return callback(err)
    }
    var students = JSON.parse(data.toString()).students;
    student.id = students[students.length-1].id+1;
    students.push(student);
    var ret = JSON.stringify({
      students:students
    })
    fs.writeFile(path,ret,function(err){
      if(err){
        return callback(err)
      }
      callback(null);
    })
  })
}

/*
  修改学生信息
 */
  exports.edit = function(student,callback){
    console.log(student)
    fs.readFile(path,function(err,data){
      if(err){
        return callback(err)
      }
      var students = JSON.parse(data.toString()).students;
      var editStu = students.find(item=>{
        return item.id == parseInt(student.id);
      })
      console.log(editStu)
      for(var key in student){
        editStu[key] = student[key];
      }
      var ret = JSON.stringify({
        students:students
      })
      fs.writeFile(path,ret,function(err){
        if(err){
          callback(err);
        }
      })
      callback(null)
    })
  }

  /**
   * 删除学生信息
   */
  exports.delete = function(id,callback){
    fs.readFile(path,function(err,data){
      if(err){
        return callback(err)
      }
      var students = JSON.parse(data.toString()).students;
      var index = students.findIndex(item=>{
        return item.id == parseInt(id);
      })
      students.splice(index,1);
      var ret = JSON.stringify({
        students:students
      })
      fs.writeFile(path,ret,function(err){
        if(err){
          callback(err);
        }
      })
      callback(null)
    })
  }<file_sep>/02/01-像apache一样.js


  const  http = require('http');

  const server = http.createServer();
  
  const fs = require('fs')

  var wwwDir = 'D:/app/www';

  server.on('request',function(req,res){
    var url = req.url;
    var filePath = '/index.html';
    if(url !== '/'){
      filePath = url;
    }
    fs.readFile(`${wwwDir}${filePath}`,function(err,data){
      if(err){
        res.end('404 not found');
        return;
      }
      res.end(data)
    })

    
  })

  server.listen('3000',function(){
    console.log('服务器启动成功')
  })<file_sep>/03/03-用mongodb重构crud/02-crud-express/student.js
/**
 * 用mongodb数据库来存储数据
 * mongoose.model('Student',studentSchema)这个表达式返回Student
 * 设计好数据库后，router文件夹中用的是mongoose提供的API来操作数据库
 */

var mongoose = require('mongoose');
//链接到crud这个数据库
mongoose.connect('mongodb://localhost/crud',{ useNewUrlParser: true });
//设计文档结构
var Schema = mongoose.Schema;

var studentSchema = new Schema({
  name:{
    type:String,
    required:true
  },
  age:{
    type:Number,
    required:true
  },
  hobbies:{
    type:String
  }
})
//导出模型构造函数，集合名为‘students’
module.exports = mongoose.model('Student',studentSchema)<file_sep>/03/01-express/app.js
// npm install --global nodemon
//  使用这个插件，可以监视文件变化，自动重启服务器
var express = require('express')
var app = express()
var bodyParser = require('body-parser')

//通过express来使用模板
app.engine('html', require('express-art-template'));
//请求静态资源文件
app.use('/lib/', express.static('./lib/'));

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

var comments = [
  {
    name:'zz',
    message:'wwwww',
    date:'2020-1-1'
  },
  {
    name:'zz',
    message:'wwwww',
    date:'2020-1-1'
  },
  {
    name:'zz',
    message:'wwwww',
    date:'2020-1-1'
  }
]
app.get('/', function (req, res) {
  res.render('index.html', {
     comments:comments
  });
});


app.get('/post', function (req, res) {
  res.render('post.html');
});
//为post请求指定处理函数
//在express中没有内置获取请求体的API，需要安装 npm install body-parser第三方包来获取
app.post('/post', function (req, res) {
  var comment = req.body;
  comment.date = '2020-1-1';
  comments.unshift(comment);
  res.redirect('/');
});




app.listen(3000,function(){
  console.log('启动服务器')
})<file_sep>/README.md
# node-express
nodejs学习   使用express和mongodb
<file_sep>/02/03-在apache案例中加入引擎模板.js
  //服务端渲染和客户端渲染的区别
  //+客户端渲染(异步获取数据)不利于SEO搜索引擎的优化，需要多次请求，但请求速度快，可局部刷新页面
  //+服务端渲染可以被爬虫抓取，客户端很难被爬虫搜索
  //+真正的网站是两者结合来做的
  var http = require('http');
  var fs = require('fs');
  var template = require('art-template');
  var server = http.createServer();
  var wwwDir = 'D:/app/www';
  server.on('request',function(req,res){
    //每次向服务器请求资源的时候都要读取文件
   if(req.url === '/'){
    fs.readFile('./tpl2.html',function(err,data){
      if(err){
        console.log('读取文件失败');
        return;
      }
      //fs.readdir得到目录列表中的文件名和目录名
      fs.readdir(wwwDir,function(err,file){
        if(err){
          return res.end('not found file')
        }
        var ret = template.render(data.toString(),{
          files:file
        })
      

        res.end(ret);
      })
    })
   }else if(req.url.indexOf('/lib/') !== -1){//为了请求静态资源
     fs.readFile('../'+req.url,function(err,data){
       if(err){
         return res.end('not found');
       }
       res.end(data);
     })
   }
  })

  server.listen('3000',function(){
    console.log('启动服务')
  })
<file_sep>/02/02-在node中使用模板引擎.js
  

  //npm install art-template
  var template = require('art-template');
  var fs = require('fs');

  fs.readFile('./tpl.html',function(err,data){
    if(err){
      console.log('读不到文件');
      return;
    }
    //data默认是二进制数据，render方法需要接受字符串
    var ret = template.render(data.toString(),{
      name:'jack',
      age:23,
      hobbies:['读书','画画','写字']
    })
    console.log(ret);
  })
  

<file_sep>/03/02-crud-express/router.js

/**
 * 路由映射表
 * get  /student
  get  /student/add
  post /student/add
  get  /student/edit
  post  /student/edit
  get   /student/delete
 * 
 
 */

var express = require('express');
var router = express.Router();
var fs = require('fs');
var student = require('./student.js')
var image=['/public/img/x1.jpg','/public/img/x2.jpg','/public/img/x3.jpg','/public/img/x4.jpg']

router.get('/student', function (req, res) {
  student.find(function(err,data){
    if(err){
      return res.send(err)
    }
    res.render('index.html',{
      image:image,
      students:data
    })
  })
  
})

router.get('/student/add', function (req, res) {
  res.render('add.html',{
    image:image
  })
})

router.post('/student/add', function (req, res) {
  student.add(req.body,function(err){
    if(err){
      return res.send(err)
    }
    res.redirect('/student');
    
  })
})


router.get('/student/edit', function (req, res) {
  student.findById(req.query.id,function(err,data){
    if(err){
      return res.send(err);
    }
    res.render('edit.html',{
      student:data,
    })
  })
})


router.post('/student/edit', function (req, res) {
  var edit = req.body;
  student.edit(edit,function(err){
    if(err){
      return res.send(err);
    }
    res.redirect('/student')
  })
})


router.get('/student/delete', function (req, res) {
  student.delete(req.query.id,function(err){
    if(err){
      return res.send(err)
    }
    res.redirect('/student')
  })
})

module.exports = router;