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版)
22
|
第
3
章
加入顺序至关重要
。如果把
404
处理函数放在路由之前
,主页和“关于”页将不再正常,
那些
URL
都会
“走”到
404
页。现在,虽然我们的路由还十分简单,但由于它们也支持
通配符,因此也会产生顺序的问题。举个例子,如果想给“关于”页增加子页面,比如
/about/contact
和
/about/directions
,该怎么做?写成下面这样是不会按预期工作的:
app.get('/about*', (req, res) => {
// 发送内容……
}) app.get('/about/contact', (req, res) => {
// 发送内容……
}) app.get('/about/directions', (req, res) => {
// 发送内容……
})
在这个例子中,
/about/contact
和
/about/directions
这两个路由永远得不到匹配,因为第一个
处理函数在路径中使用了通配符:
/about*
。
Express
可以区分
404
和
500
这两个处理函数
,依靠的是回调函数接收的参数个数。错误
处理路由将在第
10
章和第
12
章中进一步讨论。
现在可以重新启动服务器,看看主页和“关于”页是否正常了。
目前为止我们所做的事情虽然没有
Express
也很容易完成
,但是
Express
正在默默地提供一
些帮助。回想前一章:为了确定请求的是什么资源,必须对
req.url
做规范化处理。我们
不得不手动去除
URL
的查询串和末尾斜杠
,并把它转换成小写。现在
Express
的路由自动 ...
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

Publisher Resources

ISBN: 9787115565099