kobemini 2019-06-27
上面一片文章已经介绍怎样创建nodejs服务端服务,这篇将express搭建路由第一章搭建nodejs服务
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); });
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;
下一章express搭建前端项目3