五、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() 的使用
var express = require('express');
var app = express();
// 在中间件之前,不会受到中间件的影响
app.get('/',(req,res)=>{
console.log(123);
});
// 应用中间件
// 请求/user时,会先调用中间件
app.use('/user',(req,res,next)={
console.log(req);
/* 注意:中间件存在多个是一定要next() */
next();
});
// 调用之前县调用中间件
app.get('/user',(req,res)=>{
console.log('user');
});
app.listen(8000,()=>{
console.log('server is create http://127.0.0.1:8000');
});
app.method() 的使用方法
var express = require('express');
var app = express();
// 在中间件之前,不受中间件影响
app.get('/',function(req,res){
console.log(123);
})
// 应用中间件
// 只有在 post 请求user 时才起作用
app.post('/user',function (req, res, next) {
console.log(req);
next();
});
// 调用之前先调用中间件
// 接受所有请求方式请求user
app.all('/user',function(req,res){
console.log('user');
})
app.listen('8000', () => {
console.log('127.0.0.1:8000')
})
(2)路由中间件
路由器层中间件的工作方式与应用层中间件基本相同,差异之处在于它绑定到 express.Router() 的实例。
使用 router.use() 和 router.method() 函数装入路由器层中间件;
我们之前项目的代码,就是在使用路由中间件:
/* http_处理请求。 */
var express = require('express');
var router = express.Router;
router
.get('/',chuli.getall)
.get('/getone',chuli.getone)
.get('/delone',chuli.delone)
.get('/setone',chuli.setone_get)
.post('/setone',chuli.setone_post)
.get('/login',chuli.login_get)
.post('/login',chuli.login_post)
应用路由中间件:
var express = require('express');
var router = require('./http_请求处理');
var app = express();
app.use(router);
(3)内置中间件
除 express.static() 外,先前 Express 随附的所有中间件函数现在以单独模块的形式提供:中间件函数的列表。
从版本4.x开始,Express不再依赖 content ,除了 express.static(), Express 以前内置的中间件现在已经全部单独作为模块安装使用。
Express 中唯一内置的中间件函数是 express.static() 。此函数基于 serve-static,负责提供 Express 应用程序的静态资源。
对于每个应用程序,可以有多个静态目录:
app.use(express.static('public'));
app.use(express.static('uploads'));
app.use(express.static('files'));
(4)第三方中间件
使用第三方中间件向 Express 应用程序添加功能。
安装具有所需功能的 Node.js 模块,然后在应用层或路由器层的应用程序中将其加装入。
var cookieSession = require('cookie-session');
// 注册中间件
app.use(cookieSession({
name: 'session', // 客户端cookie的名称
keys: ['xilingzuishuai'] // 用于加密的关键字
}))
类似的中间件还有:
- body-parser —— 解析请求体 body 中的数据,并将其保存为Request对象的body属性。
-
// parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })) // parse application/json app.use(bodyParser.json())
-
- 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跨域被访问
const express = require('express')
const app = express()
app.use((req, res, next) => {
// 设置是否运行客户端设置 withCredentials
// 即在不同域名下发出的请求也可以携带 cookie
res.header("Access-Control-Allow-Credentials",true)
// 第二个参数表示允许跨域的域名,* 代表所有域名
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, OPTIONS') // 允许的 http 请求的方法
// 允许前台获得的除 Cache-Control、Content-Language、Content-Type、Expires、Last-Modified、Pragma 这几张基本响应头之外的响应头
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With')
if (req.method == 'OPTIONS') {
res.sendStatus(200)
} else {
next()
}
})
二、koa 基础与实例
Koa 是一个新的 web 框架,由 Express 幕后的原班人马打造, 致力于成为 web 应用和 API 开发领域中的一个更小、更富有表现力、更健壮的基石。 通过利用 async 函数,Koa 帮你丢弃回调函数,并有力地增强错误处理。 Koa 并没有捆绑任何中间件, 而是提供了一套优雅的方法,帮助您快速而愉快地编写服务端应用程序。
(1)基础用法
搭建服务、启动服务
npm install koa
/* test.js */
const Koa = require('koa');
const app = new Koa();
app.listen(8000);
启动:
node test.js
context 对象(cxt)
Koa 提供一个 Context 对象,表示一次对话的上下文(包括 HTTP 请求和 HTTP 回复)。通过加工这个对象,就可以控制返回给用户的内容。
Context 对象所包含的:
/* test.js */
const Koa = require('koa');
const app = new Koa();
app.use((cxt,next)=>{
console.log(cxt);
})
app.listen(8000);
结果:
{
request: { // 内置了request
method: 'GET',
url: '/',
header: {
host: '127.0.0.1:8000',
connection: 'keep-alive',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36',
'sec-fetch-user': '?1',
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',
'sec-fetch-site': 'none',
'sec-fetch-mode': 'navigate',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'zh-CN,zh;q=0.9'
}
},
response: {
status: 200,
message: 'OK',
header: [Object: null prototype] {
'content-type': 'text/plain; charset=utf-8',
'content-length': '11'
}
},
app: { subdomainOffset: 2, proxy: false, env: 'development' },
originalUrl: '/',
req: '<original node req>',
res: '<original node res>',
socket: '<original node socket>'
}
从上述可以看出context对象包含了request、response、app等属性,所以可以通过context来调用或者修改属性值。
Hello World
/* test.js */
const Koa = require('koa');
const app = new Koa();
app.use((cxt,next)=>{
/* 响应 hello world */
cxt.response.body = 'hello world';
// ctx.response.body可以简写成ctx.body
})
app.listen(8000);
HTTP Response 的类型
Koa 默认的返回类型是text/plain
(纯文本的形式),如果想返回其他类型的内容,可以先用ctx.request.accepts
判断一下,客户端希望接受什么数据(根据 HTTP Request 的Accept
字段),然后使用ctx.response.type
指定返回类型。
const Koa = require('koa')
const app = new Koa()
//声明一个main中间件,如果你急于了解中间件可以跳转到(三)
const main = (ctx,next) =>{
if (ctx.request.accepts('json')) {
ctx.response.type = 'json';
ctx.response.body = { data: 'Hello World' };
} else if (ctx.request.accepts('html')) {
ctx.response.type = 'html';
ctx.response.body = '<p>Hello World</p>';
} else if (ctx.request.accepts('xml')) {
ctx.response.type = 'xml';
ctx.response.body = '<data>Hello World</data>';
} else{
ctx.response.type = 'text';
ctx.response.body = 'Hello World';
};
}; //直接运行页面中会显示json格式,因为我们没有设置请求头,所以每一种格式都是ok的。
app.use(main)//app.use()用来加载中间件。
app.listen(8000)
网页模板
实际开发中,返回给用户的网页往往都写成模板文件。我们可以让 Koa 先读取模板文件,然后将这个模板返回给用户。
const fs = require('fs');
const Koa = require('koa');
const app = new Koa();
const main = ctx => {
ctx.response.type = 'html';
ctx.response.body = fs.createReadStream('./index.html');
};
app.use(main);
app.listen(8000);
模板引擎
npm install ejs koa-views
/* 模板引擎 */
const Koa = require('koa')
const path = require('path')
const app = new Koa()
// 加载模板引擎
app.use(require('koa-views')(path.join(__dirname, './view'), {
extension: 'ejs'
}))
app.use( async ( ctx ) => {
let students = ['Errrl','Errrl','Errrl','Errrl','Errrl','lisi']
await ctx.render('index', {
students,
})
})
app.listen(8000)
./view/index.ejs:
<body>
<ul>
<%
for(var i = 0; i < students.length; i++){
%>
<li><%= students[i] %></li>
<%
}
%>
</ul>
</body>
(2)路由
原生路由
通过context内置的request进行路由的映射。
const Koa = require('koa');
const app = new Koa();
app.use((cxt,next)=>{
if(cxt.request.url == '/'){
cxt.body = '<h1>首页</h1>';
}else if(cxt.request.url == '/communicate'){
cxt.body = '<h1>联系我们</h1>';
}else{
cxt.body = '404 not found';
}
})
app.listen(8000);
koa-router 路由
npm install koa-router
1. 内置路由:
const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()
app.use(router.routes()).use(router.allowedMethods());
//routes()返回路由器中间件,它调度与请求匹配的路由。
//allowedMethods()处理的业务是当所有路由中间件执行完成之后,若ctx.status为空或者404的时候,丰富response对象的header头.
router.get('/',(ctx,next)=>{//.get就是发送的get请求
ctx.response.body = '<h1>首页</h1>'
})
router.get('/my',(ctx,next)=>{
ctx.response.body = '<h1>联系我们</h1>'
})
app.listen(8000);
2. 模块化路由:
/* test.js */
/**外置路由 */
const luyou = require('./test2');
const Koa = require('koa');
const app = new Koa();
app.use(luyou.routes()).use(luyou.allowedMethods());
app.listen(8000);
/* test2.js */
/**外置路由 */
var router = require('koa-router')();
router
.get('/',(cxt)=>{
cxt.body = '<h1>首页</h1>';
})
.get('/communicate',(cxt)=>{
cxt.body = '<h1>联系我们</h1>';
})
module.exports = router;
3. 层级路由
/* test.js */
/**外置路由 */
const router = require('koa-router')();
const Koa = require('koa');
const admin = require('./routes/test2');
const news = require('./routes/test3');
const app = new Koa();
router.get('/',(cxt)=>{
cxt.body = '<h1>首页</h1>';
})
router.use('/admin',admin.routes());
router.use('/news',news);
app.use(router.routes()).use(router.allowedMethods());
app.listen(8000);
/* test2.js */
var router = require('koa-router')();
router
.get('/',(cxt)=>{
cxt.body = '<h1>首页</h1>';
})
.get('/communicate',(cxt)=>{
cxt.body = '<h1>联系我们</h1>';
})
module.exports = router;
var router=require('koa-router')();
router.get('/',(ctx)=>{
ctx.body={"title":"这是一个api"};
})
router.get('/newslist',(ctx)=>{
ctx.body={"title":"这是一个新闻接口"};
})
router.get('/focus',(ctx)=>{
ctx.body={"title":"这是一个轮播图的api"};
})
module.exports=router.routes();
加载静态资源
如果网站提供静态资源(图片、字体、样式表、脚本......),为它们一个个写路由就很麻烦,也没必要koa-static模块封装了这部分的请求。
const fs = require('fs');
const Koa = require('koa');
const app = new Koa();
const static = require('koa-static');
const router = require('koa-router')();
const path = require('path');
/* 加载静态资源 */
app.use(static(path.join(__dirname ,'./public')));
app.use(router.routes()).use(router.allowedMethods());
router.get('/',(ctx)=>{
ctx.response.type = 'html';
ctx.response.body = fs.createReadStream('./public/index2.html');
})
app.listen(8000);
./public/index2.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<p class="p">Errrl</p>
</body>
</html>
./public/style.css
.p{
color: red;
}
重定向跳转
有些场合,服务器需要重定向访问请求。比如,用户登陆以后,将他重定向到登陆前的页面。ctx.response.redirect()
方法可以发出一个跳转,将用户导向另一个路由。ctx.response.redirect('/path') 方法可以发出一个跳转,将用户导向另一个路由。
/**重定向跳转 */
const Koa = require('koa');
const app = new Koa();
const router = require('koa-router')();
router.get('/login',(ctx)=>{
/* 重定向 */
ctx.response.redirect('/');
})
router.get('/',(ctx)=>{
ctx.body = '定向成功';
})
app.use(router.routes());
app.listen(8000);
(3)中间件
Logger 功能
Koa 的最大特色,也是最重要的一个设计,就是中间件。为了理解中间件,我们先看一下 Logger (打印日志)功能的实现。
./logger/koaLogger.js
module.exports = (ctx,next)=>{
console.log(`${Date.now()} ${ctx.request.url} ${ctx.request.method} ${ctx.request.header}`);
}
./test.js:
/**logger中间件 */
const Koa = require('koa');
const app = new Koa();
const koalogger = require('./koalogger');
app.use(koalogger);
app.listen(8000);
结果:
中间件的概念
处在 HTTP Request 和 HTTP Response 中间,用来实现某种中间功能的函数,就叫做"中间件"。
基本上,Koa 所有的功能都是通过中间件实现的,前面例子里面的加载静态资源也是中间件。每个中间件默认接受两个参数,第一个参数是 Context 对象,第二个参数是 context 函数。只要调用 next 函数,就可以把执行权转交给下一个中间件。
多个中间件会形成一个栈结构,以"先进后出"的顺序执行。
例子:
const Koa = require('koa');
const app = new Koa();
app.use((ctx, next)=>{
console.log('>> one');
next();
console.log('<< one');
})
app.use((ctx, next)=>{
console.log('>> two');
next();
console.log('<< two');
})
app.use((ctx, next)=>{
console.log('>> three');
next();
console.log('<< three');
})
app.listen(8000);
输出结果:
>> one
>> two
>> three
<< three
<< two
<< one
异步中间件
迄今为止,所有例子的中间件都是同步的,不包含异步操作。如果有异步操作(比如读取数据库),中间件就必须写成async 函数。配合ES6语法就可以很好地解决异步问题。
npm install fs.promise
/**异步中间件 */
const fs = require('fs.promised');
const Koa = require('koa');
const app = new Koa();
const main = async(ctx, next)=> {
ctx.response.type = 'html';
ctx.response.body = await fs.readFile('./index.html', 'utf8');
};
app.use(main);
app.listen(8000)
上面代码中,fs.readFile 是一个异步操作,所以必须写成 await fs.readFile() ,然后中间件必须写成 async 函数。
如果存在延时器,就将掩延时器定义成一个promise对象。然年进行async、awaite。
const Koa = require('koa');
const app = new Koa();
function delay(){
return new Promise((reslove,reject)=>{
setTimeout(()=>{
reslove()
},1000)
})
}
app.use(async(ctx, next)=>{
ctx.body = '1'
await next()
ctx.body += '2'
})
app.use(async(ctx, next)=>{
ctx.body += '3'
await delay()
await next()
ctx.body += '4'
})
app.listen(8000)
中间件的合成
koa-compose 模块可以将多个中间件合成一个。
npm install koa-compose
/**中间件的合成 */
const Koa = require('koa');
const compose = require('koa-compose');
const app = new Koa();
const logger = (ctx, next) => {
console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`);
/* 注意一定要next() */
next();
}
const main = ctx => {
ctx.response.body = 'Hello World';
};
const middlewares = compose([logger, main]);//合成中间件
app.use(middlewares);//加载中间件
app.listen(8000);
(4)Web App 的功能
cookie
ctx.cookies 用来读写 Cookie。
/**cookie */
const Koa = require('koa');
const app = new Koa();
const main = function(ctx) {
//读取cookie//没有返回0
const n = Number(ctx.cookies.get('view') || 0) + 1;
ctx.cookies.set('view', n);//设置cookie
ctx.response.body = n + ' views';//显示cookie
}
app.use(main);
app.listen(8000);
获取表单数据
Web 应用离不开处理表单。本质上,表单就是 POST 方法发送到服务器的键值对。koa-body模块可以用来从 POST 请求的数据体里面提取键值对。
npm install koa-body
const Koa = require('koa');
const koaBody = require('koa-body');
const app = new Koa();
const main = async function (ctx) {
const body = ctx.request.body;
if (!body.name) {
ctx.throw(400, '.name required')
};
ctx.body = { name: body.name, age: body.age, sex: body.sex };
};
app.use(koaBody());
app.use(main);
app.listen(8000);
/**输出:
{
"name": "Errrl",
"age": "20",
"sex": "male"
}
*/
文件上传
koa-body模块还可以用来处理文件上传。
const Koa = require('koa');
const koaBody = require('koa-body');
const Router = require('koa-router');
const fs = require('fs');
const path = require('path');
const router = new Router()
const app = new Koa();
app.use(koaBody({
multipart: true,//解析多部分主体,默认false
formidable: {
maxFileSize: 1000* 1024 * 1024 // 设置上传文件大小最大限制,默认10M
}
}));
app.use(router.routes()).use(router.allowedMethods());
router.post('/uploadfile', (ctx, next) => {
// 上传单个文件
const file = ctx.request.files.file; // 获取上传文件
// 创建可读流
const reader = fs.createReadStream(file.path);
let filePath = path.join(__dirname, 'public/') + `/${file.name}`;
// 创建可写流
const upStream = fs.createWriteStream(filePath);
// 可读流通过管道写入可写流
reader.pipe(upStream);
return ctx.body = "上传成功!";
});
app.listen(8000)
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form action="http://127.0.0.1:8000/uploadfile" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" value="" multiple="multiple" />
<input type="submit" value="提交" />
</form>
</body>
</html>