前端点滴(Node.js)(五)—- 构建 Web 应用(五)Express中间件、koa 基础与实例

释放双眼,带上耳机,听听看~!

五、Express中间件、koa 基础与实例

一、Express 中间件

语法:

  • app.use()

  • app.use(function(){})

    • 无论发送任何请求都会执行的中间件。
  • app.use('/path',function(){})

  • 只要在请求path路由时才会执行的中间件(无论是POST/GET/其他请求)。

  • app.method()

  • app.get()

    • 只有在GET请求时会执行的中间件。
    • app.post()
    • 只有在POST请求时才会执行的中间件。

(1)应用中间件

app.use() 的使用


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
1var express = require('express');
2var app = express();
3
4// 在中间件之前,不会受到中间件的影响
5app.get('/',(req,res)=>{
6    console.log(123);
7});
8
9// 应用中间件
10// 请求/user时,会先调用中间件
11app.use('/user',(req,res,next)={
12    console.log(req);
13    /* 注意:中间件存在多个是一定要next() */
14    next();
15});
16
17// 调用之前县调用中间件
18app.get('/user',(req,res)=>{
19    console.log('user');
20});
21
22app.listen(8000,()=>{
23    console.log('server is create http://127.0.0.1:8000');
24});
25
26

 app.method() 的使用方法


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
1var express = require('express');
2var app = express();
3
4// 在中间件之前,不受中间件影响
5app.get('/',function(req,res){
6    console.log(123);
7})
8
9// 应用中间件
10// 只有在 post 请求user 时才起作用
11app.post('/user',function (req, res, next) {
12    console.log(req);
13    next();
14});
15
16// 调用之前先调用中间件
17// 接受所有请求方式请求user
18app.all('/user',function(req,res){
19    console.log('user');
20})
21
22app.listen('8000', () => {
23    console.log('127.0.0.1:8000')
24})
25

(2)路由中间件

路由器层中间件的工作方式与应用层中间件基本相同,差异之处在于它绑定到 express.Router() 的实例。

使用 router.use() 和 router.method() 函数装入路由器层中间件;

我们之前项目的代码,就是在使用路由中间件:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
1/* http_处理请求。 */
2var express = require('express');
3var router = express.Router;
4
5router
6.get('/',chuli.getall)
7.get('/getone',chuli.getone)
8.get('/delone',chuli.delone)
9.get('/setone',chuli.setone_get)
10.post('/setone',chuli.setone_post)
11.get('/login',chuli.login_get)
12.post('/login',chuli.login_post)
13
14

应用路由中间件:


1
2
3
4
5
1var express = require('express');
2var router = require('./http_请求处理');
3var app = express();
4app.use(router);
5

(3)内置中间件

除 express.static() 外,先前 Express 随附的所有中间件函数现在以单独模块的形式提供:中间件函数的列表。

从版本4.x开始,Express不再依赖 content ,除了 express.static(), Express 以前内置的中间件现在已经全部单独作为模块安装使用。

Express 中唯一内置的中间件函数是 express.static() 。此函数基于 serve-static,负责提供 Express 应用程序的静态资源。

对于每个应用程序,可以有多个静态目录:


1
2
3
4
1app.use(express.static('public'));
2app.use(express.static('uploads'));
3app.use(express.static('files'));
4

(4)第三方中间件

使用第三方中间件向 Express 应用程序添加功能。

安装具有所需功能的 Node.js 模块,然后在应用层或路由器层的应用程序中将其加装入。


1
2
3
4
5
6
7
8
1var cookieSession = require('cookie-session');
2
3// 注册中间件
4app.use(cookieSession({
5    name: 'session', // 客户端cookie的名称
6    keys: ['xilingzuishuai'] // 用于加密的关键字
7}))
8

类似的中间件还有:

  • body-parser —— 解析请求体 body 中的数据,并将其保存为Request对象的body属性。


1
2
3
4
5
6
1// parse application/x-www-form-urlencoded
2app.use(bodyParser.urlencoded({ extended: false }))
3
4// parse application/json
5app.use(bodyParser.json())
6
  • compression —— 压缩HTTP响应。
  • connect-rid —— 生成唯一的请求ID。
  • cookie-parser —— 解析客户端cookie中的数据,并将其保存为Request对象的cookie属性
  • cookie-session —— 建立基于cookie的会话。可用于实现登录功能,视图计数器。
  • cors —— 解析消息头部的访问来源。
  • csurf —— 保护免受CSRF攻击。
  • errorhandler —— 开发错误处理/调试。
  • method-override
  • morgan —— HTTP请求记录器。
  • multer —— 处理多部分表单数据。可以在req.file调用上传文件的信息。类似功能的有formidable ==》(推荐使用)
  • response-time —— 记录HTTP响应时间。
  • serve-favicon
  • serve-index 
  • serve-static —— 服务静态文件。可以直接使用express.static()来代替。
  • session
  • timeout —— 设置HTTP请求处理的超时时间。
  • vhost

(5)自定义中间件

允许express跨域被访问


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1const express = require('express')
2const app = express()
3
4app.use((req, res, next) => {
5    // 设置是否运行客户端设置 withCredentials
6    // 即在不同域名下发出的请求也可以携带 cookie
7    res.header("Access-Control-Allow-Credentials",true)
8    // 第二个参数表示允许跨域的域名,* 代表所有域名  
9    res.header('Access-Control-Allow-Origin', '*')
10    res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, OPTIONS') // 允许的 http 请求的方法
11    // 允许前台获得的除 Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma 这几张基本响应头之外的响应头
12    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With')
13    if (req.method == 'OPTIONS') {
14        res.sendStatus(200)
15    } else {
16        next()
17    }
18})
19

二、koa 基础与实例

Koa 是一个新的 web 框架,由 Express 幕后的原班人马打造, 致力于成为 web 应用和 API 开发领域中的一个更小、更富有表现力、更健壮的基石。 通过利用 async 函数,Koa 帮你丢弃回调函数,并有力地增强错误处理。 Koa 并没有捆绑任何中间件, 而是提供了一套优雅的方法,帮助您快速而愉快地编写服务端应用程序。

(1)基础用法

搭建服务、启动服务

npm install koa


1
2
3
4
5
1/* test.js */
2const Koa = require('koa');
3const app = new Koa();
4app.listen(8000);
5

启动:

node test.js

context 对象(cxt)

Koa 提供一个 Context 对象,表示一次对话的上下文(包括 HTTP 请求和 HTTP 回复)。通过加工这个对象,就可以控制返回给用户的内容。

Context 对象所包含的:


1
2
3
4
5
6
7
8
1/* test.js */
2const Koa = require('koa');
3const app = new Koa();
4app.use((cxt,next)=>{
5    console.log(cxt);
6})
7app.listen(8000);
8

结果:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
1{
2  request: { // 内置了request
3    method: 'GET',
4    url: '/',
5    header: {
6      host: '127.0.0.1:8000',
7      connection: 'keep-alive',
8      'upgrade-insecure-requests': '1',
9      'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
10      'sec-fetch-user': '?1',
11      accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
12      'sec-fetch-site': 'none',
13      'sec-fetch-mode': 'navigate',
14      'accept-encoding': 'gzip, deflate, br',
15      'accept-language': 'zh-CN,zh;q=0.9'
16    }
17  },
18   response: {
19    status: 200,
20    message: 'OK',
21    header: [Object: null prototype] {
22      'content-type': 'text/plain; charset=utf-8',
23      'content-length': '11'
24    }
25  },
26  app: { subdomainOffset: 2, proxy: false, env: 'development' },
27  originalUrl: '/',
28  req: '<original node req>',
29  res: '<original node res>',
30  socket: '<original node socket>'
31}
32

从上述可以看出context对象包含了request、response、app等属性,所以可以通过context来调用或者修改属性值。

Hello World


1
2
3
4
5
6
7
8
9
10
11
12
1/* test.js */
2const Koa = require('koa');
3const app = new Koa();
4app.use((cxt,next)=>{
5
6    /* 响应 hello world */
7    cxt.response.body = 'hello world';
8
9    // ctx.response.body可以简写成ctx.body
10})
11app.listen(8000);
12

HTTP Response 的类型

Koa 默认的返回类型是text/plain (纯文本的形式),如果想返回其他类型的内容,可以先用ctx.request.accepts判断一下,客户端希望接受什么数据(根据 HTTP Request 的Accept字段),然后使用ctx.response.type指定返回类型。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
1const Koa = require('koa')
2const app = new Koa()
3//声明一个main中间件,如果你急于了解中间件可以跳转到(三)
4const main = (ctx,next) =>{
5if (ctx.request.accepts('json')) {
6    ctx.response.type = 'json';
7    ctx.response.body = { data: 'Hello World' };
8  } else if (ctx.request.accepts('html')) {
9    ctx.response.type = 'html';
10    ctx.response.body = '<p>Hello World</p>';
11  } else if (ctx.request.accepts('xml')) {
12    ctx.response.type = 'xml';
13    ctx.response.body = '<data>Hello World</data>';
14  } else{
15    ctx.response.type = 'text';
16    ctx.response.body = 'Hello World';
17  };
18}; //直接运行页面中会显示json格式,因为我们没有设置请求头,所以每一种格式都是ok的。  
19
20app.use(main)//app.use()用来加载中间件。
21app.listen(8000)
22

网页模板

实际开发中,返回给用户的网页往往都写成模板文件。我们可以让 Koa 先读取模板文件,然后将这个模板返回给用户。


1
2
3
4
5
6
7
8
9
10
11
12
1const fs = require('fs');
2const Koa = require('koa');
3const app = new Koa();
4
5const main = ctx => {
6    ctx.response.type = 'html';
7    ctx.response.body = fs.createReadStream('./index.html');
8};
9
10app.use(main);
11app.listen(8000);
12

模板引擎

npm install ejs koa-views


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1/* 模板引擎 */
2const Koa = require('koa')
3const path = require('path')
4const app = new Koa()
5
6// 加载模板引擎
7app.use(require('koa-views')(path.join(__dirname, './view'), {
8  extension: 'ejs'
9}))
10
11app.use( async ( ctx ) => {
12  let students = ['Errrl','Errrl','Errrl','Errrl','Errrl','lisi']
13  await ctx.render('index', {
14    students,
15  })
16})
17
18app.listen(8000)
19

./view/index.ejs:


1
2
3
4
5
6
7
8
9
10
11
12
1<body>
2    <ul>
3        <%
4            for(var i = 0; i < students.length; i++){
5        %>
6           <li><%= students[i] %></li>
7        <%
8            }
9        %>
10    </ul>
11</body>
12

(2)路由

原生路由

通过context内置的request进行路由的映射。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
1const Koa = require('koa');
2const app = new Koa();
3
4app.use((cxt,next)=>{
5    if(cxt.request.url == '/'){
6        cxt.body = '<h1>首页</h1>';
7    }else if(cxt.request.url == '/communicate'){
8        cxt.body = '<h1>联系我们</h1>';
9    }else{
10        cxt.body = '404 not found';
11    }
12})
13app.listen(8000);
14

koa-router 路由

npm install koa-router

1. 内置路由:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1const Koa = require('koa')
2const Router = require('koa-router')
3
4const app = new Koa()
5const router = new Router()
6
7app.use(router.routes()).use(router.allowedMethods());
8//routes()返回路由器中间件,它调度与请求匹配的路由。
9//allowedMethods()处理的业务是当所有路由中间件执行完成之后,若ctx.status为空或者404的时候,丰富response对象的header头.
10
11router.get('/',(ctx,next)=>{//.get就是发送的get请求
12  ctx.response.body = '<h1>首页</h1>'
13})
14router.get('/my',(ctx,next)=>{
15  ctx.response.body = '<h1>联系我们</h1>'
16})
17
18app.listen(8000);
19

2. 模块化路由:


1
2
3
4
5
6
7
8
1/* test.js */
2/**外置路由 */
3const luyou = require('./test2');
4const Koa = require('koa');
5const app = new Koa();
6app.use(luyou.routes()).use(luyou.allowedMethods());
7app.listen(8000);
8

1
2
3
4
5
6
7
8
9
10
11
12
13
1/* test2.js */
2/**外置路由 */
3var router = require('koa-router')();
4router
5    .get('/',(cxt)=>{
6        cxt.body = '<h1>首页</h1>';
7    })
8    .get('/communicate',(cxt)=>{
9        cxt.body = '<h1>联系我们</h1>';
10    })
11
12module.exports = router;
13

3. 层级路由


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1/* test.js */
2/**外置路由 */
3const router = require('koa-router')();
4const Koa = require('koa');
5const admin = require('./routes/test2');
6const news = require('./routes/test3');
7const app = new Koa();
8
9router.get('/',(cxt)=>{
10    cxt.body = '<h1>首页</h1>';
11})
12router.use('/admin',admin.routes());
13router.use('/news',news);
14
15app.use(router.routes()).use(router.allowedMethods());
16app.listen(8000);
17

1
2
3
4
5
6
7
8
9
10
11
12
1/* test2.js */
2var router = require('koa-router')();
3router
4    .get('/',(cxt)=>{
5        cxt.body = '<h1>首页</h1>';
6    })
7    .get('/communicate',(cxt)=>{
8        cxt.body = '<h1>联系我们</h1>';
9    })
10
11module.exports = router;
12

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
1var router=require('koa-router')();
2
3router.get('/',(ctx)=>{
4  ctx.body={"title":"这是一个api"};
5})
6
7router.get('/newslist',(ctx)=>{
8  ctx.body={"title":"这是一个新闻接口"};
9})
10
11router.get('/focus',(ctx)=>{
12  ctx.body={"title":"这是一个轮播图的api"};
13})
14
15module.exports=router.routes();
16

加载静态资源

如果网站提供静态资源(图片、字体、样式表、脚本……),为它们一个个写路由就很麻烦,也没必要koa-static模块封装了这部分的请求。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1const fs = require('fs');
2const Koa = require('koa');
3const app = new Koa();
4const static = require('koa-static');
5const router = require('koa-router')();
6const path = require('path');
7
8/* 加载静态资源 */
9app.use(static(path.join(__dirname ,'./public')));
10app.use(router.routes()).use(router.allowedMethods());
11router.get('/',(ctx)=>{
12    ctx.response.type = 'html';
13    ctx.response.body = fs.createReadStream('./public/index2.html');
14})
15
16app.listen(8000);
17

./public/index2.html:


1
2
3
4
5
6
7
8
9
10
11
12
13
1<!DOCTYPE html>
2<html lang="en">
3<head>
4    <meta charset="UTF-8">
5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
6    <title>Document</title>
7    <link rel="stylesheet" href="/style.css">
8</head>
9<body>
10    <p class="p">Errrl</p>
11</body>
12</html>
13

./public/style.css


1
2
3
4
1.p{
2    color: red;
3}
4

重定向跳转

有些场合,服务器需要重定向访问请求。比如,用户登陆以后,将他重定向到登陆前的页面。ctx.response.redirect()方法可以发出一个跳转,将用户导向另一个路由。ctx.response.redirect('/path') 方法可以发出一个跳转,将用户导向另一个路由。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
1/**重定向跳转 */
2const Koa = require('koa');
3const app = new Koa();
4const router = require('koa-router')();
5router.get('/login',(ctx)=>{
6    /* 重定向 */
7    ctx.response.redirect('/');
8})
9router.get('/',(ctx)=>{
10    ctx.body = '定向成功';
11})
12app.use(router.routes());
13app.listen(8000);
14

(3)中间件

Logger 功能

Koa 的最大特色,也是最重要的一个设计,就是中间件。为了理解中间件,我们先看一下 Logger (打印日志)功能的实现。

./logger/koaLogger.js


1
2
3
4
1module.exports = (ctx,next)=>{
2    console.log(`${Date.now()} ${ctx.request.url} ${ctx.request.method} ${ctx.request.header}`);
3}
4

./test.js:


1
2
3
4
5
6
7
1/**logger中间件 */
2const Koa = require('koa');
3const app = new Koa();
4const koalogger = require('./koalogger');
5app.use(koalogger);
6app.listen(8000);
7

结果:

前端点滴(Node.js)(五)---- 构建 Web 应用(五)Express中间件、koa 基础与实例

中间件的概念

处在 HTTP Request 和 HTTP Response 中间,用来实现某种中间功能的函数,就叫做"中间件"。

基本上,Koa 所有的功能都是通过中间件实现的,前面例子里面的加载静态资源也是中间件。每个中间件默认接受两个参数,第一个参数是 Context 对象,第二个参数是 context 函数。只要调用 next 函数,就可以把执行权转交给下一个中间件。

多个中间件会形成一个栈结构,以"先进后出"的顺序执行。

例子:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
1const Koa = require('koa');
2const app = new Koa();
3
4app.use((ctx, next)=>{
5  console.log('>> one');
6  next();
7  console.log('<< one');
8})
9
10app.use((ctx, next)=>{
11  console.log('>> two');
12  next();
13  console.log('<< two');
14})
15app.use((ctx, next)=>{
16  console.log('>> three');
17  next();
18  console.log('<< three');
19})
20app.listen(8000);
21
22输出结果:
23>> one
24>> two
25>> three
26<< three
27<< two
28<< one
29
30

异步中间件

迄今为止,所有例子的中间件都是同步的,不包含异步操作。如果有异步操作(比如读取数据库),中间件就必须写成async 函数。配合ES6语法就可以很好地解决异步问题。

npm install fs.promise


1
2
3
4
5
6
7
8
9
10
11
12
13
1/**异步中间件 */
2const fs = require('fs.promised');
3const Koa = require('koa');
4const app = new Koa();
5
6const main = async(ctx, next)=> {
7    ctx.response.type = 'html';
8    ctx.response.body = await fs.readFile('./index.html', 'utf8');
9};
10
11app.use(main);
12app.listen(8000)
13

上面代码中,fs.readFile 是一个异步操作,所以必须写成 await fs.readFile() ,然后中间件必须写成 async 函数。

如果存在延时器,就将掩延时器定义成一个promise对象。然年进行async、awaite。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
1const Koa = require('koa');
2const app = new Koa();
3function delay(){
4    return new Promise((reslove,reject)=>{
5      setTimeout(()=>{
6        reslove()
7      },1000)
8    })
9}
10
11app.use(async(ctx, next)=>{
12  ctx.body = '1'
13  await next()
14  ctx.body += '2'
15})
16
17app.use(async(ctx, next)=>{
18   ctx.body += '3'
19   await delay()
20   await next()
21   ctx.body += '4'
22})
23app.listen(8000)
24
25

中间件的合成

koa-compose 模块可以将多个中间件合成一个。

npm install koa-compose


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
1/**中间件的合成 */
2const Koa = require('koa');
3const compose = require('koa-compose');
4const app = new Koa();
5
6const logger = (ctx, next) => {
7  console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);
8  /* 注意一定要next() */
9  next();
10}
11
12const main = ctx => {
13  ctx.response.body = 'Hello World';
14};
15
16const middlewares = compose([logger, main]);//合成中间件
17
18app.use(middlewares);//加载中间件
19app.listen(8000);
20
21

(4)Web App 的功能

cookie

ctx.cookies 用来读写 Cookie。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
1/**cookie */
2const Koa = require('koa');
3const app = new Koa();
4
5const main = function(ctx) {
6  //读取cookie//没有返回0
7  const n = Number(ctx.cookies.get('view') || 0) + 1;
8  ctx.cookies.set('view', n);//设置cookie
9  ctx.response.body = n + ' views';//显示cookie
10}
11
12app.use(main);
13app.listen(8000);
14

获取表单数据

Web 应用离不开处理表单。本质上,表单就是 POST 方法发送到服务器的键值对。koa-body模块可以用来从 POST 请求的数据体里面提取键值对。

npm install koa-body


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
1const Koa = require('koa');
2const koaBody = require('koa-body');
3const app = new Koa();
4
5const main = async function (ctx) {
6    const body = ctx.request.body;
7    if (!body.name) {
8        ctx.throw(400, '.name required')
9    };
10    ctx.body = { name: body.name, age: body.age, sex: body.sex };
11};
12
13app.use(koaBody());
14app.use(main);
15app.listen(8000);
16
17/**输出:
18{
19    "name": "Errrl",
20    "age": "20",
21    "sex": "male"
22}
23 */
24

文件上传

koa-body模块还可以用来处理文件上传。


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
1const Koa = require('koa');
2const koaBody = require('koa-body');
3const Router = require('koa-router');
4const fs = require('fs');
5const path = require('path');
6const router = new Router()
7const app = new Koa();
8
9app.use(koaBody({
10    multipart: true,//解析多部分主体,默认false
11    formidable: {
12        maxFileSize: 1000* 1024 * 1024    // 设置上传文件大小最大限制,默认10M
13    }
14}));
15
16app.use(router.routes()).use(router.allowedMethods());
17
18router.post('/uploadfile', (ctx, next) => {
19    // 上传单个文件
20    const file = ctx.request.files.file; // 获取上传文件
21    // 创建可读流
22    const reader = fs.createReadStream(file.path);
23    let filePath = path.join(__dirname, 'public/') + `/${file.name}`;
24    // 创建可写流
25    const upStream = fs.createWriteStream(filePath);
26    // 可读流通过管道写入可写流
27    reader.pipe(upStream);
28    return ctx.body = "上传成功!";
29});
30
31app.listen(8000)
32

html:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1<!DOCTYPE html>
2<html lang="en">
3
4<head>
5    <meta charset="UTF-8">
6    <meta name="viewport" content="width=device-width, initial-scale=1.0">
7    <meta http-equiv="X-UA-Compatible" content="ie=edge">
8    <title>Document</title>
9</head>
10
11<body>
12    <form action="http://127.0.0.1:8000/uploadfile" method="post" enctype="multipart/form-data">
13        <input type="file" name="file" id="file" value="" multiple="multiple" />
14        <input type="submit" value="提交" />
15    </form>
16</body>
17
18</html>
19

 

给TA打赏
共{{data.count}}人
人已打赏
安全技术

使用shell脚本进行服务器系统监控——文件系统监控(3)

2021-8-18 16:36:11

安全技术

C++ 高性能服务器网络框架设计细节

2022-1-11 12:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索