Node.js Web开发
概览
- Node.js
 - Express
 - mongoDB
 - jQuery
 - Semantic UI
 - Visual Code
 
功能需求
- 首页文章显示
 - 注册登录功能
 - 文章编辑发表
 - 评论
 - 文章删除
 
一、
创建项目,执行如下代码:
npm init
1、新建 index.js 作为项目入口文件, 使用MVC架构。
引入框架和组件,添加中间件(如connect-flash、) 设置模板目录设置模板引擎为 ejs
2、创建路由文件夹 “routes” 和文件 “/routes/index.js”, 核心代码编辑如下:
module.exports = function (app) {
   app.get('/', (req, res) => {
    res.send("hello, express");
})
    app.use('/posts', require('./posts')); // routes文件夹下 模块路由
    app.use(function(req, res){
    if(!res.headerSent){
      res.render('404');
    }
  });
  };
模块路由代码示例:
// GET /posts 所有用户或者特定用户的文章页
//   eg: GET /posts?author=xxx
router.get('/', function(req, res, next) {
  // res.send("Hello world" );
  var author = req.query.author
  PostModel.getPosts(author)
    .then(function (posts){
      res.render('posts', {
        posts: posts
      });
    })
    .catch(next);
});
3、使用mongolass组件连接数据库,实现增删改查
mongolass.connect(config.mongodb) // 连 接 数 据 库 
示例代码:
exports.User = mongolass.model('User', {
  name: { type: 'string' },
  password: { type: 'string' },
  avatar: { type: 'string' },
  gender: { type: 'string', enum: ['m', 'f', 'x'] },
  bio: { type: 'string' }
})