-
Notifications
You must be signed in to change notification settings - Fork 2
/
node-note2.html
242 lines (198 loc) · 10.1 KB
/
node-note2.html
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta http-equiv="Cache-Control" content="no-siteapp">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=1, minimum-scale=1, maximum-scale=1">
<meta name="referrer" content="never">
<meta name="robots" content="index,follow">
<link rel="shortcut icon" href="/favicon.png?v=198964">
<link rel="apple-itouch-icon" href="/favicon.png?v=198964">
<link href="/bundle/index.min.css" rel="stylesheet">
<link href="https://fonts.loli.net/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" rel="stylesheet">
<link href="https://cdn.staticfile.org/prism/1.16.0/themes/prism.min.css" rel="stylesheet">
<link href="https://cdn.staticfile.org/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<script>
function ensureDate(e){return"object"!=typeof e&&(e=new Date(e)),e}function dateFormat(e,t){void 0===t&&(t=e,e=ensureDate());let n={M:(e=ensureDate(e)).getMonth()+1,d:e.getDate(),h:e.getHours(),m:e.getMinutes(),s:e.getSeconds(),q:Math.floor((e.getMonth()+3)/3),S:e.getMilliseconds()},r=new RegExp("([yMdhmsqS])+","g");return t=t.replace(r,function(t,r){let u=n[r];if(void 0!==u)return t.length>1&&(u=(u="0"+u).substring(u.length-2)),u;if("y"===r){return(e.getFullYear()+"").substring(4-t.length)}return t})}
</script>
<meta name="keywords" content="node.js学习笔记(2) - Koa2中间件,Node,Koa2,">
<meta name="description" content="node.js学习笔记(2) - Koa2中间件,Node,Koa2,">
<meta name="author" content="江矿先森.">
<title>node.js学习笔记(2) - Koa2中间件</title>
<link href="/bundle/iconfont.css" rel="stylesheet">
<link href="/bundle/reward.css" rel="stylesheet">
<script src='/bundle/av.min.js'></script>
<script src='/bundle/valine.min.js'></script>
</head>
<body>
<article class="container">
<header class="header-wrap asset">
<nav class="main-nav">
<ul class="menu vertical naive">
<li class="menu-item"><a href="/">Home</a></li>
<li class="menu-item"><a href="/archive.html">Archive</a></li>
<li class="menu-item"><a href="/tag.html">Tag</a></li>
<li class="menu-item"><a href="/atom.xml">RSS</a></li>
</ul>
</nav>
<div class="bgs" style="background-image: url(https://s11.ax1x.com/2024/02/04/pFlmAII.jpg);"></div>
<div class="vertical">
<div class="header-wrap-content inner">
<h3 class="title">Stay before every beautiful thoughts.</h3>
<h3 class="subtitle">Just be nice, always think twice!</h3>
</div>
</div>
</header>
<article class="main article">
<h1 class="title">node.js学习笔记(2) - Koa2中间件</h1>
<section class="info">
<span class="avatar" style="background-image: url(https://s11.ax1x.com/2024/02/04/pFlmVit.jpg);"></span> <a class="name" href="javascript:;">江矿先森.</a>
<span class="date"><script>document.write(dateFormat( 1525573434 *1000, 'yyyy-MM-dd'))</script></span>
<span class="tags"><a class="tages" href="/tag/Node/index.html">Node</a><a class="tages" href="/tag/Koa2/index.html">Koa2</a></span>
</section>
<article class="content"><h1>middleware(中间件)</h1>
<blockquote>
<p>正是因为中间件的扩展性才使得 <code>Koa2</code>的代码简单灵活。</p>
</blockquote>
<p>在 <code>app.js</code> 中,有这样一段代码:</p>
<pre><code class="language-js">app.use(async (ctx, next)=>{
await next()
ctx.response.type = 'text/html'
ctx.response.body = '<h1>Hello World</h1>'
})
</code></pre>
<p>它的作用是:每收到一个 <code>http</code> 请求,<code>Koa2</code>都会调用通过 <code>app.use()</code> 注册的 <code>async</code> 函数,同时为该函数传入 <code>ctx</code> 和 <code>next</code> 两个参数。而这个 <code>async</code> 函数就是我们所说的中间件。</p>
<p>下面我们简单介绍一下传入中间件的两个参数。</p>
<p><br></p>
<h2>ctx</h2>
<p><code>ctx</code> 作为上下文使用,包含了基本的 <code>ctx.request</code> 和 <code>ctx.response</code>。另外,还对 <code>Koa2</code>内部对一些常用的属性或者方法做了代理操作,使得我们可以直接通过 <code>ctx</code> 获取。比如,<code>ctx.request.url</code> 可以写成 <code>ctx.url</code>。</p>
<p>除此之外,<code>Koa2</code>还约定了一个中间件的存储空间 <code>ctx.state</code>。通过 <code>state</code> 可以存储一些数据,比如用户数据,版本信息等。如果你使用 <code>webpack</code> 打包的话,可以使用中间件,将加载资源的方法作为 <code>ctx.state</code> 的属性传入到 <code>view</code> 层,方便获取资源路径。</p>
<h2>next</h2>
<p><code>next</code> 参数的作用是将处理的控制权转交给下一个中间件,而 <code>next()</code> 后面的代码,将会在下一个中间件及后面的中间件(如果有的话)执行结束后再执行。</p>
<p><strong>注意:</strong> 中间件的顺序很重要!</p>
<p>我们重写 <code>app.js</code> 来解释下中间件的流转过程:</p>
<pre><code class="language-js">import Koa from 'koa'
const app = new Koa()
// 记录执行的时间
app.use(async (ctx, next) => {
let stime = new Date().getTime()
await next()
let etime = new Date().getTime()
ctx.response.type = 'text/html'
ctx.response.body = '<h1>Hello World</h1>'
console.log(`请求地址: ${ctx.path},响应时间:${etime - stime}ms`)
});
app.use(async (ctx, next) => {
console.log('中间件1 doSoming')
await next();
console.log('中间件1 end')
})
app.use(async (ctx, next) => {
console.log('中间件2 doSoming')
await next();
console.log('中间件2 end')
})
app.use(async (ctx, next) => {
console.log('中间件3 doSoming')
await next();
console.log('中间件3 end')
})
app.listen(3000, () => {
console.log('server is running at http://localhost:3000')
})
</code></pre>
<p><br></p>
<p>运行起来后,控制台显示:</p>
<pre><code class="language-txt">server is running at http://localhost:3000
</code></pre>
<p>然后打开浏览器,访问 <code>http://localhost:3000</code>,控制台显示内容更新为:</p>
<pre><code class="language-txt">server is running at http://localhost:3000
中间件1 doSoming
中间件2 doSoming
中间件3 doSoming
中间件3 end
中间件2 end
中间件1 end
请求地址: /,响应时间:2ms
</code></pre>
<p>从结果上可以看到,流程是一层层的打开,然后一层层的闭合,像是剥洋葱一样 —— 洋葱模型。</p>
<p>此外,如果一个中间件没有调用 <code>await next()</code>,会怎样呢?答案是『后面的中间件将不会执行』。</p>
<p>修改 <code>app.js</code> 如下,我们去掉了第三个中间件里面的 <code>await</code>:</p>
<pre><code class="language-js">import Koa from 'koa'
const app = new Koa()
// 记录执行的时间
app.use(async (ctx, next)=>{
let stime = new Date().getTime()
await next()
let etime = new Date().getTime()
ctx.response.type = 'text/html'
ctx.response.body = '<h1>Hello World</h1>'
console.log(`请求地址: ${ctx.path},响应时间:${etime - stime}ms`)
});
app.use(async (ctx, next) => {
console.log('中间件1 doSoming')
await next();
console.log('中间件1 end')
})
app.use(async (ctx, next) => {
console.log('中间件2 doSoming')
// 注意,这里我们删掉了 next
// await next()
console.log('中间件2 end')
})
app.use(async (ctx, next) => {
console.log('中间件3 doSoming')
await next();
console.log('中间件3 end')
})
app.listen(3000, () => {
console.log('server is running at http://localhost:3000')
})
</code></pre>
<p>重新运行代码后,控制台显示如下:</p>
<pre><code class="language-txt">server is running at http://localhost:3000
中间件1 doSoming
中间件2 doSoming
中间件2 end
中间件1 end
请求地址: /,响应时间:1ms
</code></pre>
</article>
<section class="author">
<div class="avatar" style="background-image: url(https://s11.ax1x.com/2024/02/04/pFlmVit.jpg);"></div>
<a class="name" href="javascript:;">江矿先森.</a>
<div class="intro">前(台)端(菜), 喜欢瞎折腾新技术. 乜野都识少少, 先可以扮代表:p</div>
</section>
<section class="social">
<a href="https://github.com/joname1" target="_blank">
<i class="iconfont i-github"></i>
</a>
<a href="javascript:alert('你电脑中了不知名的病毒, 并抛出了警告 atob(“d3hJZDogZXJyb3IuZXJyb3I=”)')" target="_blank">
<i class="iconfont i-wechat"></i>
</a>
<a href="https://www.zhihu.com/topic/19550901" target="_blank">
<i class="iconfont i-zhihu"></i>
</a>
<a href="javascript:alert('对方不想跟你讲话, 并向你扔来一段乱码 atob(“ZXJyb3JAZXJyb3IuZXJyb3I=”)')" target="_blank">
<i class="iconfont i-email"></i>
</a>
</section>
<div id="comment"></div>
</article>
</article>
<footer class="footer clearfix">
<span class="copyright">
<script>
document.write(new Date().getFullYear());
</script> <i class="fa fa-copyright"></i> Made with <i class="fa fa-heart"></i> using <joname />
<span id="runtime_span"></span>
</span>
</footer>
<script src="/bundle/index.min.js"></script>
<script src="https://cdn.staticfile.org/prism/1.16.0/prism.min.js"></script>
<script>
new Valine({el: '#comment',appId: 'PieJ3iHvVTJ9C5yBudK6sxaT-MdYXbMMI',appKey: 'Yt25unM4vc9wzBvC2lL20Frc',placeholder: 'ヾノ≧∀≦)o来啊, 快活啊, 反正有大把时光!!',path: window.location.pathname,avatar: 'retro',pageSize: 10,guest_info: ['nick', 'mail'],lang: 'en'});
</script>
</body>
</html>