上面一片文章已经介绍怎样创建nodejs服务端服务,这篇将express搭建路由第一章搭建nodejs服务
配置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 fs = require("fs");
//gzip压缩
var compression = require('compression');
//处理异常
var domain = require('domain');
var app = express();
设置模板引擎
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
使用相关中间件
// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
//log日志
app.use(logger('dev'));
//HTTP请求体解析中间
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
//对http传入的cookie进行解析后赋值给req.cookies
app.use(cookieParser());
//引入public文件里面的静态资源包括css,js,image etc.
app.use(express.static(path.join(__dirname, 'public')));
引入路由文件
//路由文件读取
var file = fs.readdirSync('./routes');
for (var i in file) {
var name = file[i].replace('.js', '');
require('./routes/' + name)(app, domain);
}
抓取错误信息
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
错误处理,渲染404页面
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.statusCode = 404;
res.render('htmlerror');
});
抛出模块
module.exports = app;