Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Express 学习-02-中间件 #15

Open
Jsmond2016 opened this issue Nov 9, 2021 · 0 comments
Open

Express 学习-02-中间件 #15

Jsmond2016 opened this issue Nov 9, 2021 · 0 comments

Comments

@Jsmond2016
Copy link
Owner

Express 中间件

参考文档:使用中间件-express

next函数

作用:暂停,然后传递至下一个中间件

使用前面的例子:

const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = 3000


app.use(express.static('public'));


// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({ extended: false })

// next 函数表示进入下一个中间件
app.get('/index', (req, res, next) => {
	req.data = 123
	next()
}, function (req, res, next) {
	console.log('通过中间件取到的值:', req.data)
	res.send('end')
})



app.listen(port, () => console.log(`Example app listening on port ${port}!`))

路由中间件

类似一个mini 的 app,使用方式相对简单

使用方式:

var router = express.Router()

// 指定 请求方式 + 请求路径 时处理方式
router.get(path, fn)
router.post(path,fn)
// 指定请求路径,任意请求方式时处理
router.use(path, fn)

具体代码:

var app = express()
// 使用路由中间件
var router = express.Router()

// a middleware function with no mount path. This code is executed for every request to the router
router.use(function (req, res, next) {
  console.log('Time:', Date.now())
  next()
})

// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
router.use('/user/:id', function (req, res, next) {
  console.log('Request URL:', req.originalUrl)
  next()
}, function (req, res, next) {
  console.log('Request Type:', req.method)
  next()
})

// a middleware sub-stack that handles GET requests to the /user/:id path
router.get('/user/:id', function (req, res, next) {
  // if the user ID is 0, skip to the next router
  if (req.params.id === '0') next('route')
  // otherwise pass control to the next middleware function in this stack
  else next()
}, function (req, res, next) {
  // render a regular page
  res.render('regular')
})

// handler for the /user/:id path, which renders a special page
router.get('/user/:id', function (req, res, next) {
  console.log(req.params.id)
  res.render('special')
})

// mount the router on the app
app.use('/', router)

错误捕获中间件

使用方式:app.use(function (err, req,res, next) {})

demo:

const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = 3000


app.use(express.static('public'));


// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({ extended: false })

app.get('/index', (req, res, next) => {
	connsole.log(11) // 这里写错一个单词
})

// 使用错误中间件捕获异常
app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})


app.listen(port, () => console.log(`Example app listening on port ${port}!`))

当访问:localhost:3000/index 时候,返回:Something broke!

注意:错误中间件的位置可以放在所有请求前面,也可以放在后面,例如:

  • 请求处理前格式判断是否错误等
  • 请求处理中可能遇到报错,错误捕获放在最后兜住前面的错误

cookie-parser 中间件

安装:

npm install cookie-parser

使用:

const express = require('express')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const app = express()
const port = 3000


app.use(express.static('public'));
// 使用 cookie-parser 中间件
app.use(cookieParser())

// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({ extended: false })

app.get('/index', (req, res, next) => {
    // 使用 cookie-parser 中间件后,这里才能拿到 cookies
	res.send(req.cookies)
})


app.listen(port, () => console.log(`Example app listening on port ${port}!`))

在浏览器手动写入 cookie 作为测试

输入地址访问:localhost:3000/index 拿到 cookie

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant