express 入门

Express 框架是什么

Express 是一个基于Node平台的web应用开发框架,它提供了一系列的强大特性,

npm install express

express 初体验

const express = require('express')
const app = express()
app.get('/', (req, res) => {
  // send 内部检测响应内容的类型
  // send 自动设置http状态吗
  // send 自动设置响应类型以及编码
  res.send('hello express')
})
app.get('/list', (req, res) => {
  res.send({name: "zs", age: 20})
})
app.listen(3000)
console.log('web service start success !!!')

什么是中间件

中间件就是一堆方法 可以接收客户端发来的请求 , 可以对请求作出响应 , 也可以将请求继续交给下一个中间件继续处理

可以针对同一个请求设置多个中间件 , 对同一个请求进行多次处理 ; 默认情况下 , 请求从上到下一次匹配中间件 , 一旦匹配成功终止匹配 ;

可以调用 next 放大将请求的控制权交给下一个中间件 , 直到遇到结束请求的中间件

app.get('/request', (req, res, next) => {
	req.name = 'zs'
	next()
})
app.get('/request', (req, res) => {
	res.send(req.name)
})

app.use 中间件用法

app.use 匹配所有的请求方式 , 可以直接传入请求处理函数, 代表接收所有的请求

app.use((req, res, next) => {	
	console.log('first' + req.url)
	next()
})

app.use 第一个参数也可以传入请求地址 , 代表不论什么请求方式 , 只要是这个请求地址就接收这个请求

app.use('/request', (req, res) => {
	console.log('last' + req,url)
})

中间件应用

路由保护 , 客户端在访问需要登录的页面时 , 可以使用中间件判断用户登录状态 , 用户如果未登录 , 则拦截请求 直接响应 , 禁止用户进入需要登录的页面

let isLogin = false
app.use('/admin', (req, res, next) => {
  if (isLogin) next()
  res.send('not login')
})
app.get('/admin', (req, res) => {
  res.send('login success')
})

网站维护公告 , 在所有路由的最上面 定义接收所有请求的中间件 , 直接为客户端作出响应网站正在维护中

app.use((req, res, next) => {
  res.send('正在维护中...')
})

自定义404页面 , 声明到所有的路由最后面, 匹配不到的时候, 就会匹配use中间件

app.use((req, res) => {
	res.status(404) // 指定状态吗
	res.send('not found')
})

错误处理中间件

在程序执行的过程中 , 不可避免的会出现一些无法预料的错误 , 比如数据库连接失败等 , 错误处理中间件是一个集中处理错误的地方 , 只能处理 同步代码的 err

app.get('/index', (req, res) => {
  throw new Error('未知错误')
})
app.use((err, req, res, next) => {
  res.status(500).send('服务器未知错误' + err.message)
})

当程序出现错误的时候 , 调用 next() 方法 , 并且将错误信息通过参数 的形式传递给next()方法 , 即可触发错误处理中间件

app.get('/index', (req, res, next) => {
  fs.readFile('01.txt', 'utf8', (err, result) => {
    err != null ? next(err) : next(result)
  })
})
app.use((err, req, res, next) => {
  err != null ? res.send(err) : res.send(result)
})

捕获异步函数中的错误

在node.js 中 , 异步API的错误信息 都是通过回调函数获取的 , 支持Promise对象的异步api发生错误可以通过catch方法捕获

try catch 可以捕获异步函数以及其他同步代码在执行过程中发生的错误 , 但是不能其他类型的api发生的错误

app.get('/', async (req, res, next) => {
  try {
    await fs.readFile('-01.txt', 'utf8', (err, data) => {
      res.send(data)
    })
  } catch(ex) {
    console.log(ex)
    next(ex)
  }
})
app.use((err, req, res) => {
  res.status(500).send(err.message)
})

构建模块化路由

const app = express()
const home = express.Router()
app.use('/home', home)
home.get('/index', (req, res) => {
  res.send(req.url)
})
app.listen(3000)
// index.js
const express = require('express')
const home = require('./route/home')
const admin = require('./route/admin')
const app = express()
app.use('/admin', admin)
app.use('/home', home)
app.listen(3000)
// home.js
const express = require('express')
const home = express.Router()
home.get('/index', (req, res) => {
  res.send('wel come to home index page')
})
module.exports = home
// admin.js
const express = require('express')
const admin = express.Router()
admin.get('/index', (req, res) => {
  res.send('wel come to admin page')
})
module.exports = admin

get 请求

// req.query 获取参数 获取过来的就是对象形式
app.get('/index', (req, res) => {
  res.send(req.query) // {"name":"zs","age":"23"}
})

post 请求

express 中接收 post 请求参数需要借助第三方包 body-parser

npm install body-parser
app.use(bodyParser.urlencoded({extended: false}))
app.post('/index', (req, res) => {
  res.send(req.body)
})

express 路由参数

app.get('/index/:id/:name', (req, res) => {
  res.send(req.params)
})
// localhost/index/id/name

静态资源的处理

// 访问时,不需要加 public 示例: localhost:3000/pages/index.html
app.use(express.static(path.join(__dirname, '/public')))
// 第一个参数必须带 / 示例: localhost:3000/static/pages/index.html
app.use('/static', express.static(path.join(__dirname, '/public')))

模板引擎

为了使用 art-template 模板引擎能够更好的express结合 , 模板引擎官方在原来的基础上封装了 express-art-template

npm install art-template
npm install express-art-template
// app.js
// 告诉express框架使用什么模板引擎,渲染什么后缀的文件
app.engine('art', require('express-art-template'))
// 告诉 express 框架模板存放的位置 第一个参数是固定的 第二个参数表示存放的文档 文件夹
app.set('views', path.join(__dirname, 'views'))
// 告诉 express 框架模板的默认后缀是什么
app.set('view engine', 'art')
app.get('/index', (req, res) => {
  // 1. render() 帮助我们拼接路径
  // 2. 拼接模板后缀
  // 3. 哪一个模板和哪一个数据进行拼接
  // 4. 拼接的结果响应给客户端
  res.render('index', {
    msg: 'message'
  })
})
// index.art
{{msg}} // message

app.locals 对象

将变量设置到 app.locals 对象下面, 这个数据在所有的模板中都可以获取到

// app.js
app.locals.users = [
	{
		name: 'zs',
		age: 23
	},
	{
		name: 'ls',
		age: 24
	}
]
// index.art 可以直接访问 users 不用在render出来
{{msg}}
<ul>
  {{each users}}
  <li>
    {{$value.name}}
    {{$value.age}}
  </li>
  {{/each}}
</ul>
posted @ 2020-04-21 00:23  计算机相关人员  阅读(285)  评论(0编辑  收藏  举报