express

作者: 壹枕星河 | 来源:发表于2019-04-16 20:53 被阅读0次
Express 应用程序生成器

安装:$ npm install express-generator -g

npm list -g --depth=0 查看全局安装的插件

npx 临时使用的命令,临时安装插件时使用,用完之后删除

npx express-generator backend -e 添加对 ejs 模板引擎的支持,会生成以下文件: image.png
//创建HTTP错误请求
var createError = require('http-errors');
//express
var express = require('express');
//原生模块path
var path = require('path');
//express的cookie处理的中间键(middleware)
var cookieParser = require('cookie-parser');
//日志中间键
var logger = require('morgan');

//引用首页的路由
var indexRouter = require('./routes/index');
//引用users的路由
var usersRouter = require('./routes/users');

var app = express();

// view engine setup 设置view渲染引擎为ejs
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');


//app.use是express实例上的方法,表示应用中间键
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


//把路由也当初中间键来挂载
app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
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.render('error');
});

module.exports = app;

相关文章

网友评论

      本文标题:express

      本文链接:https://www.haomeiwen.com/subject/jqmiwqtx.html