1 // 1.引入所有的包依赖文件 2 const createError = require('http-errors'); 3 const express = require('express'); 4 const path = require('path'); 5 const cookieParser = require('cookie-parser'); 6 const logger = require('morgan'); 7 8 // 2. 引入路由文件 9 const indexRouter = require('./routes/index'); 10 const usersRouter = require('./routes/users'); 11 12 // 3. 创建web服务器 13 const app = express(); 14 15 // 4. 设置模板引擎 16 app.set('views', path.join(__dirname, 'views')); 17 app.set('view engine', 'ejs'); 18 19 // 5. 使用各种中间件 20 app.use(logger('dev')); 21 app.use(express.json()); 22 app.use(express.urlencoded({ extended: false })); 23 app.use(cookieParser()); 24 app.use(express.static(path.join(__dirname, 'public'))); 25 26 // 6. 配置路由 27 app.use('/', indexRouter); 28 app.use('/users', usersRouter); 29 30 // 处理找不到页面 31 app.use(function(req, res, next) { 32 next(createError(404)); 33 }); 34 35 // 统一处理错误 36 app.use(function(err, req, res, next) { 37 // set locals, only providing error in development 38 res.locals.message = err.message; 39 res.locals.error = req.app.get('env') === 'development' ? err : {}; 40 41 // render the error page 42 res.status(err.status || 500); 43 //view 中error.js 44 res.render('error'); 45 }); 46 47 module.exports = app;
脚手架搭建的app.js
express demo --view=ejs