Skip to Content
Node与Express开发(第2版)
book

Node与Express开发(第2版)

by Ethan Brown
June 2021
Intermediate to advanced
290 pages
9h 21m
Chinese
Posts & Telecom Press
Content preview from Node与Express开发(第2版)
中间件
|
99
那么在管线中,一个请求是如何“终结”的呢?这就轮到传入每个中间件的
next
函数发挥
作用了:如果你没有调用
next()
,请求就终结于这个中间件。
10.1
 基本原理
要理解
Express
如何工作,关键是要学习灵活地思考中间件和路由处理函数。以下几点需
要牢记。
•
路由处理函数(
app.get
、
app.post
等,常常统称为
app.METHOD
)可以被认为是只处理
特定
HTTP
动
词(
GET
,
POST
等)的中间件。反过来,中间件也可以被认为是处理所有
HTTP
动词的路由处理函数
(基本上等同于
app.all
,它也处理所有
HTTP
动词。对于
某些少见的动词,如
PURGE
,中间件跟
app.all
的处理效果有微小的差异,但对于常用
的动词,二者处理效果一样)。
•
路由处理函数需要一个路径作为第一个参数。如果你想让这个路径匹配任何路由,就使
用
/*
。
中间件也可以接收一个路径作为第一个参数,但这是可选的(如果略去,它将匹
配任何路径,就像指定了
*
一样)
。
•
路由处理函数和中间件接收一个回调函数,这个回调函数可以接收
2
个、
3
个或
4
个参
数(从技术上来说,你也可以让它没有或只有一个参数,但这种形式没有什么用)。如
果有
2
个或
3
个参数
,前
2
个参数就是
request
和
response
对象,第三个参数就是
next
函数。如果有
4
个参数,这个回调函数就成了
错误处理
中间件,第一个参数就成了错误
对象,紧接着是
request
、
response
和
next
这些对象。
•
如果你
没有
调用
next()
,管线就会终结,不再有路由处理函数和中间件的处理 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

面向对象的思考过程(原书第5版)

面向对象的思考过程(原书第5版)

马特 魏斯费尔德
精通模块化JavaScript

精通模块化JavaScript

Nicolás Bevacqua
前端架构设计

前端架构设计

Micah Godbolt

Publisher Resources

ISBN: 9787115565099