用 Express 4.x 搭建项目 —— 后台架构

Koa 作为下一代 Node.js Web 框架,而且由 express 团队原班人马打造,相信会比 express 做得更好。然而我还没用上 Koa,,,所以只能来说下 express 了。算是一篇笔记吧,记录做项目时学到的东西。

项目的环境是:node v4.1.2 , express 4.x

前期工作:装好各种环境

项目大体架构:

 

因为开始做之前是设想着前后端分离,前后端只用ajax进行数据交互,所以就后台结构就全写成api形式。前端页面的路由由angular 1.x来实现。

 

express 配置 express.js

/**
 * Created by hwen on 15/12/12.
 */

'use strict';

var express = require('express');
var favicon = require('serve-favicon');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var path = require('path');
var session = require('express-session');
var sessionStore = require('sessionstore');
var uuid = require('uuid');
var config = require('./environment');
var morgan = require('morgan');
var busboy = require('connect-busboy');

module.exports = function(app) {
    console.log("root is:"+config.root);
    app.set('views', path.join(config.root , 'public/src'));
    // app.engine('html', require('ejs').renderFile);
    app.set('view engine', 'html');
    //app.use(compression());


    //解析http请求体(req.body)
    app.use(bodyParser.urlencoded({
        limit: '5000mb',
        extended: true
    }));
    app.use(bodyParser.json({
        limit:'5000mb'
    }));

    //配置 session
    app.use(session({
        genid: function(req) {
            return uuid.v1();
        },
        cookie:{maxAge: 900000},
        secret: 'i-waka',
        rolling:true,
        resave: true,
        saveUninitialized: true
    }));    

    app.use(cookieParser());
    //app.use(busboy({ immediate: true }));  设置 immediate 会导致图片保存不完整
    app.use(busboy());

    // config environment
    app.use(favicon(config.root + '/public/src/assets/images/favicon.ico'));

    app.use(express.static(path.join(config.root, 'public/src')));   //控制静态资源加载根目录
    app.set('appPath', config.root + 'public/src');
    app.use(morgan('dev'));
};

  

 

routes.js

 

/**
 * Created by hwen on 15/12/12.
 */

/*
* Main application routes
 * */

'use strict';

var erros = require('./components/errors');

module.exports = function(app) {

    // insert routes below
    app.use('/api/user', require('./api/user'));
    app.use('/api/question', require('./api/question'));
    app.use('/api/answer', require('./api/answer'));
    app.use('/api/topic', require('./api/topic'));
    app.use('/api/reply', require('./api/reply'));
    app.use('/api/message', require('./api/message'));
    app.use('/api/attitude', require('./api/attitude'));

    // All undefined asset or api routes should return a 404
    app.route('/:url(api|components|app|config)/*').get(erros[404]);

    // all other routes should redirect to the index.jade
    app.route('/*')
        .get(function(req, res) {
            res.sendfile(app.get('appPath')+'/index.html');
        })
};

  

 

app.js

 

/**
 * Created by hwen on 15/12/19.
 */

'use strict';

var express =require('express');
var mongoose = require('mongoose');
var config = require('./config/environment');


//Connect to database
var uri = 'mongodb://localhost:27017/test';
mongoose.connect(uri, config.mongo.options);

//set up server
var app = express();
var server = require('http').createServer(app);
require('./config/express')(app);
require('./routes')(app);

//start server
server.listen(config.port, function() {
    console.log('Express server listening on %d', config.port);
    console.log(config);
});

// Expose app
exports = module.exports = app;

  

以 user api 为例,

app.use('/api/user', require('./api/user'));

相应的中间件写在 /user/index.js

 

/**
 * Created by hwen on 15/12/12.
 */
'use strict';

var express = require('express'),
    controller = require('./user.controller');

var router = express.Router();

router.post('/login', controller.login);
router.post("/", controller.create);
router.post("/imgUpload", controller.imgUpload);
router.post("/update", controller.update);
router.post("/password", controller.updatePassword);
router.get('/logout', controller.logout);
router.get('/currentUser', controller.currentUser);
router.get("/hello", controller.hello);
router.get("/followingTopic/:_id", controller.getFollowingTopic);
router.get("/followingTopicAll/:_id", controller.getFollowingTopicAll);
router.get("/:id", controller.get);

module.exports = router;

  

 

而 /user/*.controller.js 跟 /user/*.model.js 就分别实现 controller 层以及 model 层的功能。

至此一个大概的后台架构已经算是搭建完成了~

 

posted @ 2016-03-22 16:28  hwencc  阅读(1647)  评论(0编辑  收藏  举报