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来作了一个服务器,默认端口是:3000node

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

- 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条件语句
    • 循环语句
相关文章
相关标签/搜索