Express中server和路由分离

express是node中很强大的web开发框架,通过使用它,可以快速的的开发一个web应用

先看一下一个express应用的目录结构

bin:存放可执行文件
node_modules:存放package.json中配置的模块
public:存放image,css,js文件
routes:存放路由文件
views:存放模板文件
app.js:启动文件,文件入口
package.json:存放模块依赖,当使用命令npm install的时候,会自动检查package下配置的模块,并把模块安装到node_modules中

express会默认把负责路由功能的代码放到app.js中,随着项目越来越复杂,app.js文件就显得越臃肿,难以维护,这就需要把路由从app.js中分离出来

先看一下app.js中的代码

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

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

var app = express();

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

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

app.use('/', routes);

app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;

index.js中的代码

var express = require('express');
var router = express.Router();
 //GET home page. 
 router.get('/', function (req, res, next) {
 res.render('index', {title: 'Express'});
 });

下面进行路由的分离,把路由控制器的函数放到index.js中

第一步,先对app.js进行修改

var routes = require('./routes');改为var routes = require('./routes');

把app通过传参的方式传到index.js中,routes(app);

修改后的index.js长这样:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

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

var app = express();

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

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

routes(app);

app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;

第二步,对index.js进行改造

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

module.exports = function (app) {
    app.get("/", function (req, res) {
        res.render('index', {title: '首页'});
    });

    app.get('/about', function (req, res) {
        res.render('about', {title: '关于'});
    });
}

做一下测试,在views中把index.ejs复制一份,改为about.ejs

npm start 启动sever

一切顺利的话会看到这样:

首页

关于

done

标签: express

添加新评论