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版)
路由
|
157
//...
}
如果只是剪切和粘贴,很可能会遇到一些问题。例如,如果一些内联的处理函数中使用的
变量或方法在新的上下文中不可用,这些引用就损坏了。可以把必要的导入加进来,但先
别急,我们一会儿会把这些处理函数移进它们自己的模块,到那时再解决这个问题。
那么如何把这些路由链进来呢?很简单:在
meadowlark.js
里,只需导入路由:
require('./routes')(app)
或者可以更明确一些,增加一个命名的导入(我们把它命名为
addRoutes
,以便更好地体
现它是一个函数;如果愿意,也可以这么命名这个文件):
const addRoutes = require('./routes')
addRoutes(app)
14.8
 合乎逻辑地分组路由
为了符合第一条指导原则(使用命名函数作为路由处理函数),需要找个地方来放置这些
处理函数。一个相当极端的做法是给每个处理函数都创建一个单独的文件。我想不出来这
样做会有什么好处。把相关的功能以某种方式归为一组会更好一些,不仅提取和使用公共
函数会更容易,而且修改相关的方法也更容易。
就现在来说,让我们把功能划分到各个文件中:
handlers/main.js
将放置主页处理函数
、“关
于”页处理函数以及任何没有另外的逻辑主页的处理函数,而
handlers/vacations.js
将放置
度假产品相关的处理函数,等等。
handlers/main.js
文件大概是这样的:
const fortune = require('../lib/fortune') ...
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