express通过生成器 【 脚手架 】


express通过生成器 【 脚手架 】

1. 作用:可以帮助快速构建一个express项目

2. 脚手架的安装

  • 全局安装 【可以使用npm cnpm】
    • $ cnpm i express-generator -g
  • npx安装
    • npx是npm下的一个管理工具,它可以让我们不全局安装使用某一个包
    • npx的好处就是可以帮助我们减少使用内存
    • 但是npx要求npm的版本在5.2以上
    • npx是npm自动携带的

3.脚手架的使用

  • 全局安装的使用
    • $ express -e 项目名称 (-e:--ejs)
  • npx安装的使用
    • $ npx express -e 项目名称

4.认识项目目录结构

项目文件
    > bin
    > public
    > routes
    > views
      app.js
      package.json
- 1.先找到package.json [ 记录了项目的依赖包信息,npm脚本 ]
{
  "name": "01-web-server-ssr",
  "version": "0.0.0",
  "private": true, "scripts": { "start": "nodemon ./bin/www" }, "dependencies": { "cookie-parser": "~1.4.4", "debug": "~2.6.9", "ejs": "~2.6.1", "express": "~4.16.1", "http-errors": "~1.6.3", "morgan": "~1.9.1" } } 
- 2.找到项目启动文件 bin/www

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

var server = http.createServer(app); 
  • 它是通过http来做了一个服务器,默认端口是:3000

  • 这个文件中引入了一个app文件,这个文件是将createServer中的回调函数放到了外面,以模块化的形式使用的,这个文件我们叫它: '入口文件'

- 3.看: app.js
  • express是由路由和中间件构成的
    • 路由:可以完成页面的连接或是接口的打造
    • 中间件:中间件是一个函数,一个具有特定功能的函数
      • 中间件有三个类型
- 1.应用级中间件
app.use(logger('dev')); // 日志文件记录 app.use(express.json()); // json数据格式化 app.use(express.urlencoded({ extended: false })); // 引入文件后缀名省略 app.use(cookieParser()); // cookie处理 app.use(express.static(path.join(__dirname, 'public'))); // 指定项目静态资源文件夹为public - 2.路由中间件 // http://localhost:3000/users app.use('/', indexRouter); app.use('/users', usersRouter); app.use('/',homeRouter) - 3.错误处理中间件 // 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'); }); 
  • 中间件的参数
    • req : 全称: request 表示请求
    • res : 全称: response 表示响应
    • next: 表示request和response之间的连接 , 相当于桥梁的作用
    • next如果断开,那么请求和响应就会中断 next( false )
  • 中间件要想调用,必须通过app的use方法来调用
- 4. 路由中间件
  • 路由中间件人家是以模块化的形式使用
  • 看: routes/xx.js
    • 有两个路径,这两个路径会拼接在一起
      • 举例: /home /banner /home/banner 二级路由
    • 为什么res.render('index')
      • 配置了模板的路径
      • 配置了后缀名省略
5.看: view/xxx.ejs
  • ejs语法
  • ejs文件中可以直接在模板语法中使用数据
6。 ejs语法学习
  • 注意: ejs语法符号是不能换行的
  • 非转义输出 <%- %> 可以解析xml类型数据
  • 转义输出 <%= %> 可以解析普通类型数据
  • 流程控制 <% %>
    • if条件语句
    • 循环语句

猜你喜欢

转载自www.cnblogs.com/zwj-lcx/p/11355005.html