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版)
14
|
第
2
章
2.5.2
 事件驱动编程
Node
背后的核心哲学就是
事件驱动编程
。对你(程序员)就意味着,必须要知悉有什么
事件可能会发生以及如何响应。很多人是通过实现用户界面才第一次认识事件驱动编程
的:用户点击了某个东西,然后你处理一个
点击事件
。事件驱动编程是很好的比喻,因为
很显然程序员没法控制用户是否点击以及何时点击一个东西,因此,事件驱动编程是非常
直观的。把这个概念推广到服务器上,会略微有些难以理解,但基本原理一样。
在前面的示例代码中,事件是隐含的:正在处理的事件就是一个
HTTP
请
求。
http.
createServer
方法需要一个函数作为参数,每次创建新的
HTTP
请求时,就会调用这个函
数。简单示例只是把内容类型设置为普通文本,然后发送字符串“
Hello world!
”。
一旦你开始从事件驱动编程的角度思考,就会发现到处都是事件。用户使用你的应用时,
从一页导航到另一页,或从一块内容导航到另一块内容,就是一个事件。你的应用如何响
应这样的导航事件,就叫作
路由
。
2.5.3
 路由
路由指的是对客户端内容请求的满足机制。对基于
Web
的客户端
/
服务器端应用,客户端
在
URL
中指
定了想要的内容,具体来讲就是
URL
中的路径和查询串(第
6
章将更详细地
讨论
URL
的各个部分)
。
通常,服务器端的路由依赖于路径和查询串,但还有别的信息可以使用:
HTTP
头、
域名、
IP
地址,等等。这使得服务器端可以把更多的因素纳入考
虑,例如用户的大概位置,或是用户首选的语言。
下面对前面的“
Hello world!
”做一下扩展,让它做点儿更有意思的事情。做一个只包含主 ...
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