Appearance
CS 4288 备考条目
Lecture 12 — SPA & Webpack
页码按 PDF 实际页序计算,包含标题页。本章共 18 页。标为 【补充】 的内容用于解释机制;标为 【课件修正】 的内容指出课件代码或表述的问题。
1. Core Concepts(核心概念)
Single Page Application — SPA(单页应用)
An SPA renders different application views within a single loaded document.
SPA 在同一个已加载的文档中切换应用视图,不要求每次切换都重新加载完整 HTML 页面。(p.9–12)
- Single page does not mean a single view. — 一个文档可以包含多个逻辑页面,例如首页、个人资料页。
- Client-side routing determines the current logical page. — 客户端需要根据 URL 等信息判断当前应显示哪个视图。
- An SPA can still communicate with a server. — SPA 仍然需要加载资源、获取数据和同步状态。
- 【补充】An SPA may have multiple URLs. — “单页”不代表地址栏永远不变。
- 【补充】Client-side navigation does not guarantee zero network requests. — 不重新加载整个文档,仍可能请求数据或其他资源。
Initial loading sequence(课件的首次加载流程):(p.10–12)
- 浏览器请求站点,例如
GET www.vanderbilt.edu。 - 服务器返回 HTML 页面。
- 浏览器请求
/js/main.js。 - 服务器返回 SPA bundle。
- 客户端运行路由与视图逻辑。
On initial load or URL change(首次加载或 URL 改变时):(p.12)
- Determine the requested page — 判断用户需要哪个逻辑页面。
- Load the appropriate view template — 选择或加载相应模板。
- Fetch necessary data — 获取需要的数据,不代表每次都必须重新请求。
- Render the view — 将视图渲染到页面。
onLoad()和onURLChange()是课件中的流程伪代码名称,不是浏览器自动提供的同名路由 API。
SPA Responsibilities(SPA 的四项职责)
课件强调,无论选择什么框架,都需要处理以下职责。(p.7、15–17)
| Responsibility | 英文考试表述 | 中文要点 |
|---|---|---|
| Routing | Determine which view corresponds to the current route. | URL 与逻辑页面的对应关系 |
| Views | Render templates and data into the DOM. | 模板与数据生成页面内容 |
| Events | Connect events on elements to handler functions. | 事件类型、目标元素、处理函数 |
| Data | Manage client state and its relationship with the server. | 数据获取、缓存、同步、持久化和更新 |
- Angular, Ember, and Backbone are examples of SPA frameworks listed in the slides. — 课件列举的框架,不是穷尽列表。(p.6)
- 【补充】Webpack is a build tool, not an SPA routing framework. — 构建工具与运行时框架的职责不同。
Project Structure & Build Pipeline(目录与构建流程)
Client source code and publicly served build output have different roles.
客户端源码与提供给浏览器的构建产物分工不同。(p.3–5、8)
| 路径 / 名称 | 课件中的职责 |
|---|---|
Data | 项目数据目录 |
Src/Client | 客户端源代码 |
Src/Server | 服务器源代码 |
Client/Views | 客户端视图模板 |
Client/Models | 客户端模型 |
src/client/main.js | 客户端入口,p.4 特别圈出 |
public/js/main.js | 构建后向浏览器提供的 JS bundle |
webpack.config.js | Webpack 构建配置 |
src/server/index.js | 服务器入口 |
public/index.html | 浏览器初始 HTML |
src/client/views/landing.ejs | 客户端 landing view 模板 |
Build pipeline(构建流水线):(p.5)
- Inputs: JavaScript、libraries、templates、其他资源。
- Build configuration: 图中以
manifest表示构建所需的配置描述。 - Processing: 图中统称
Compiler。 - Output: 放入
Public/JS的main.js。
【补充】Webpack bundles modules and can invoke loaders to process different resource types.
Webpack 处理模块依赖与打包,具体资源转换可交给 loader;Babel 集成见 Lecture 13。
p.8 只列出课堂 GitHub 演示文件,没有给出完整代码或仓库 URL。因此不能把未展示的
entry、output、服务器配置等当成这份 PPT 已明确讲解的配置项。
Routing & History API(路由与浏览器历史)
The History API can change the URL without loading a new document.
History API 可以更新地址栏和历史记录,而不重新加载文档。(p.13–14,机制补充见下)
课件的 setRoute(route) 顺序:
- 比较
route !== window.location.pathname。 - 如果不同,调用
window.history.pushState({}, '', route)。 - 使用
switch(route)执行对应分支。 - 示例分支为
/index.html和/profile.html。
Code behavior(代码行为):
- Same pathname → skip the entire block. — 路由字符串等于当前 pathname 时,不入栈,也不执行视图分支。
- Different pathname → push first, then dispatch. — 先改变 URL / 历史,再执行
switch。 - No matching case → no matching view logic. — 示例没有
default;未知路由仍可能已入栈,但没有相应视图处理。 breakprevents switch fall-through. — 匹配分支结束后不继续进入下一个分支。pathnameexcludes query and fragment. — 单独比较 pathname 不能完整判断包含查询参数或 hash 的状态。
【课件修正】“Handles all URL changes and events” is a routing requirement, not something this snippet fully implements.
课件旁注表示路由系统应处理 URL 变化;给出的片段没有展示初次加载、后退/前进或 hash 事件处理。(p.13–14)
【补充】History API 易考边界:
pushState()本身不加载目标页面,也不自动请求该路径。pushState()不会自动渲染视图。pushState()本身不触发popstate,也不触发hashchange。- 浏览器后退/前进等历史遍历可触发
popstate,应用需据此更新视图。 - 新 URL 必须与当前文档同源。
- 首次加载与后退/前进不能只依赖课件的条件分支。 URL 已经是目标 pathname 时,再调用同样的
setRoute(pathname)会跳过渲染。 - 【补充】Path-based routing requires suitable server handling for direct visits and reloads. — 直接访问或刷新
/profile.html时会请求服务器,服务器需能返回应用入口或对应资源。
机制核对:MDN — pushState、MDN — popstate。
Views & Templates(视图与模板)
A template produces HTML from data; DOM insertion displays that HTML.
模板根据数据生成 HTML,DOM 操作负责把结果插入页面。(p.15)
- 使用
import ... from ...导入模板。 - 可以渲染简单 HTML fragments,也可以使用复杂 Underscore templates。
- 模板导入、模板执行、DOM 插入是三个不同步骤。
- 【补充】Importing an
.ejsfile requires appropriate build support. — 不能把这种写法理解为所有浏览器原生支持直接执行 EJS 文件。
【课件修正】Template variable mismatch(模板变量名不一致):(p.15)
- 导入名称:
landingTempl。 - 调用名称:
landingPage(data)。 - 如果没有其他定义,直接照抄会因
landingPage未定义而报错。 - 按导入名称统一,应写作:
$("#mainDiv").append(landingTempl(data))。
Events & Backbone View(事件与 Backbone 视图)
An event mapping specifies the event, selector, and handler.
事件映射需要明确:监听什么事件、哪些元素、调用哪个函数。(p.16)
课件示例:
tagName: 'tr'— View 的根元素为表格行。'click .add-one': 'addOne'— 点击.add-one匹配元素时调用addOne。'click .minus-one': 'minusOne'— 点击.minus-one匹配元素时调用minusOne。template— 通过 Underscore 编译模板。render— 使用模型属性生成 HTML,写入 View 的根元素。addOne/minusOne— 阻止默认行为,再调用模型方法。
【补充】Backbone uses delegated DOM events within the view.
这里的选择器匹配受该 View 元素范围约束,不是无条件监听整个页面。Backbone 官方文档
【课件修正】Arrow functions do not acquire the Backbone view as this.
课件把 render、addOne、minusOne 写成箭头函数,却在其中依赖 this.$el、this.model。(p.16)
- 箭头函数继承外层
this。 - Backbone 不能通过普通绑定把箭头函数的
this改成 View 实例。 - 按示例意图应使用普通方法,例如
render() { ... }、addOne(e) { ... }。 preventDefault()does not stop event propagation. — 阻止默认动作,不等于阻止冒泡。- 模型的
addOne()/minusOne()是示例自定义方法,不能当作 Backbone 所有 Model 都自带的 API。 - 模型改变是否自动触发重渲染,取决于额外事件监听;该片段没有展示。
Data Management(客户端数据管理)
SPA data management includes more than fetching data.
SPA 数据管理不只是向服务器发送请求。(p.17)
需要考虑:
- Fetching / caching / syncing with the server — 获取、缓存、与服务器同步。
- Preserving data between sessions — 跨会话持久化。
- Intelligent view re-rendering on changes — 数据变化后合理更新视图。
- Offline application usage — 离线使用。
A framework may or may not address each issue.
课件明确说这些问题可能由框架处理,也可能没有;不能推断所有 SPA 框架自动具备缓存、持久化或离线能力。
2. Comparisons & Distinctions(易混淆概念对比)
| 对比 | A | B | 考试区分点 |
|---|---|---|---|
| Client source vs. build output | src/client/main.js:源码入口 | public/js/main.js:构建产物 | 同名不代表同一文件或职责 |
| Routing vs. rendering | 确定当前逻辑页面 | 根据模板和数据更新 DOM | URL 改变不自动完成渲染 |
| Template compilation vs. execution | 模板文本变成可调用函数 | 向模板函数传入数据,生成 HTML | 两阶段不要混淆 |
.append(html) vs. .html(html) | 追加到已有内容之后 | 替换元素内部内容 | 重复 append 可能累积内容 |
| Event handling vs. data management | 响应交互、调用函数 | 改变或同步模型状态 | 点击事件本身不保证持久化 |
preventDefault() vs. stopping propagation | 阻止默认行为 | 阻止事件继续传播 | 不是同一操作 |
| SPA framework vs. Webpack | 运行时应用职责 | 构建与模块打包 | Webpack 不替代客户端路由 |
Path vs. fragment routing(p.13–14,含机制补充):
| 维度 | Path-based routing | Fragment-based routing |
|---|---|---|
| 示例 | /profile.html | /#profile |
| URL 部分 | pathname | # 后的 fragment |
| 浏览器属性 | location.pathname | location.hash |
| 服务器是否收到该部分 | HTTP 请求包含路径 | HTTP 请求不包含 fragment |
| 常见客户端机制 | History API、popstate | hash 修改、hashchange |
| 直接访问 / 刷新 | 服务器需能处理该路径 | fragment 不改变服务器收到的路径 |
| 是否等于自动渲染 | 否 | 否 |
Fragment 规则核对:MDN — URI fragment。
3. APIs & Configurations(API 与配置速查)
Routing(p.12–14)
this.setRoute('/profile.html')— 调用应用自定义路由函数;是否取数或渲染由实现决定,不是浏览器 API。window.location.pathname— 同步读取当前 URL 的路径字符串,不包含 query 或 fragment。window.history.pushState({}, '', route)— 参数依次是关联状态对象、保留参数、目标 URL;同步增加历史项并更新 URL,不自动加载文档或渲染,返回undefined。switch (route) { case '/index.html': ...; break; }— 按路由字符串执行对应分支;break结束该次 switch 分支执行。
【补充:理解课件路由所需】
window.addEventListener('popstate', handler)— 注册历史遍历处理函数;注册本身不异步取数,回调在事件发生时运行。window.location.hash— 读取 fragment,非空时包含开头的#。window.addEventListener('hashchange', handler)— 监听常规 fragment 变化;pushState()本身不会触发该事件。
Views & Templates(p.15–16)
import landingTempl from './views/landing.ejs'— 导入模板模块的默认导出;需要相应构建支持,导入本身不等于插入 DOM。landingTempl(data)— 按课件意图调用模板函数,用data生成 HTML;通常同步返回字符串,具体导出取决于 loader。$('#mainDiv').append(landingTempl(data))— 将模板结果追加到目标元素;同步修改 DOM,返回 jQuery 对象;已修正课件变量名不一致。$('#surfboard-template').html()— 无参数时读取所选元素的内部 HTML,用作模板源。_.template($('#surfboard-template').html())— 同步编译模板文本,返回可用数据调用的模板函数。this.template(this.model.attributes)— 将模型属性传入模板,生成当前视图的 HTML。this.$el.html(html)— 同步替换 View 根元素的内部 HTML,返回 jQuery 对象。return this— render 方法返回当前 View,便于链式调用;不表示浏览器自动把它挂载到页面。
Backbone Events(p.16)
以下
this按“已改为普通方法”的预期行为解释。
Backbone.View.extend({...})— 创建 View 子类并返回其构造函数,不是直接创建该 View 的实例。tagName: 'tr'— 指定自动创建的根元素标签名。events: { 'click .add-one': 'addOne' }— 将事件类型和选择器映射到 View 方法名称。events: { 'click .minus-one': 'minusOne' }— 点击对应元素后调用minusOne。e.preventDefault()— 同步取消可取消事件的默认动作,不阻止冒泡,返回undefined。this.model.addOne()— 调用自定义模型方法;具体状态变化、返回值及是否通信取决于该方法实现。this.model.minusOne()— 同上,不能仅凭名称断定自动保存到服务器。this.model.attributes— 读取 Backbone Model 的属性集合,供模板使用。
4. True / False Traps(判断题陷阱)
- True —
An SPA can display multiple views within one document.— 单文档可以承载多个逻辑页面。(p.9–12) - False —
A single-page application can have only one URL.— 客户端路由可以改变 URL。(p.13–14) - False —
An SPA never communicates with a server after loading.— 仍可能获取、缓存和同步数据。(p.17) - True —
Routing, views, events, and data are core SPA responsibilities.— 课件明确列出的四项职责。(p.7) - False —
All SPA frameworks automatically support offline usage and persistence.— 课件说这些问题可能得到处理,也可能没有。(p.17) - False —
Webpack is responsible for choosing the current SPA view at runtime.— Webpack 的构建职责不等于路由职责。(p.5、8) - True —
The initial HTML and the SPA JavaScript bundle are separate resources in the slide example.— 课件分两次请求展示。(p.10–12) - False —
Calling pushState automatically downloads and renders the target page.— 只改变历史与 URL,应用需自行渲染。(p.13–14;补充) - False —
Calling pushState automatically fires popstate.— 直接调用不触发该事件。(补充) - False —
pushState can change the current URL to any origin.— 目标 URL 受同源限制。(补充) - False —
The provided setRoute code renders even when route equals pathname.— 相等时整个条件块被跳过。(p.13–14) - False —
The provided setRoute code handles every possible route.— 没有展示未知路由的 default 处理。(p.13–14) - False —
window.location.pathname includes the query string and fragment.— 不包括。(p.13–14;补充) - False —
A fragment is sent to the server as part of the HTTP request URL.— fragment 留在客户端。(补充) - False —
Importing a template automatically inserts its HTML into the DOM.— 还需要执行模板并插入 DOM。(p.15) - False —
append replaces all existing content in the target element.— append 是追加。(p.15) - False —
The template variable names on slide 15 are consistent.— 导入landingTempl,却调用landingPage。(p.15) - True —
An event map identifies an event type, selector, and handler.— 例如 click、.add-one、addOne。(p.16) - False —
preventDefault also stops event bubbling.— 默认动作与传播是两回事。(p.16;补充) - False —
Backbone can rebind an arrow function's this to the view instance.— 箭头函数保持词法 this。(p.16;课件修正) - False —
Calling a model method necessarily updates the DOM and server.— 取决于模型实现和监听机制。(p.16–17)
5. Exam Quick Reference(考前速查)
- Four responsibilities: Routing / Views / Events / Data。(p.7)
- Entry:
src/client/main.js;bundle:public/js/main.js。(p.3–5) - Initial flow: HTML → JS bundle → determine route → template → necessary data → render。(p.10–12)
- History:
pushState(state, '', url);更新 URL / 历史,不自动加载、渲染或触发 popstate。(p.13–14) - Route snippet: same pathname → skip;unknown route → 可能已 push,但无匹配视图。(p.13–14)
- Path / hash: pathname 不含 query/hash;fragment 不发给服务器。
- Template typo:
landingTempl≠landingPage。(p.15) - DOM:
.append()追加;.html(value)替换。(p.15–16) - Events:
'event selector': 'handler';preventDefault()不停止冒泡。(p.16) - Backbone trap: 箭头函数的
this不会自动成为 View。(p.16) - Data issues: fetch / cache / sync / persistence / re-render / offline。(p.17)
Lecture 13 — SPA & Babel
本章共 15 页。人物背景页 p.9、课堂实验提示 p.15 无需作为知识点背诵。页码均含标题页。
1. Core Concepts(核心概念)
Transpiling — Source-to-source compilation(转译)
关键边界:
- Transpiling does not necessarily produce machine code. — 转译输出仍可以是 JavaScript 源码。
- Transpilation can occur between versions of the same language. — 不要求输入和输出是完全不同的语言。
- 【补充】Transpilation is a kind of compilation. — 不能把 compile 与 transpile 当成逻辑上完全互斥的类别。
- Transpilation supports compatibility with target environments. — 目标浏览器还不支持某些新语法时,可生成其支持的旧语法。(p.8)
Babel — JavaScript transformation tool(JavaScript 转换工具)
【课件限定】These are configurable capabilities, not guaranteed default behavior.
- 需要对应 parser、plugin、preset 或外部工具支持。
- 不能推断“安装 Babel 后,默认就支持所有语言并自动压缩”。
- p.14 的配置只展示 env 与 React presets,未展示 minification 配置。
- Minification and transpilation have different goals. — 压缩主要减少代码体积;降级转译主要满足目标语法兼容性。
Babel Architecture(Babel 架构)
Babel follows a modular compiler architecture.
Babel 采用模块化编译器架构。(p.11)
课件图示:
Source language / syntax → Parser → IR → Generator → Output code
- Parser — 解析输入源码。
- IR — Intermediate Representation — 中间表示,使前后端处理解耦。
- Generator — 根据处理后的表示生成输出代码。
- 图中不同输入包括 JSX、ES8 / ES7 / ESX、CoffeeScript,输出示例为 ES5。
【补充】Babel commonly represents code as an AST and applies transformations before generation.
实际理解可采用:解析为 AST → 插件转换 AST → 生成代码。课件的 IR 是概括性表达。
Targets & Browserslist(目标环境)
The target environment determines which transformations are needed.
需要哪些转换取决于目标浏览器及其版本,不是所有项目都固定输出 ES5。(p.12、14)
- Browserslist describes target browser versions. — 用查询规则描述支持范围,供 Babel 等工具使用。
last 3 versions— 每种浏览器最近三个版本,不是整个浏览器市场总共三个版本。- 目标列表随浏览器版本数据更新,并非永久固定的一组版本。
- Browserslist 不执行转译;真正执行代码转换的是 Babel 等工具。
- 【课件修正】正确名称为
Browserslist,配置文件为.browserslistrc。 — p.12 的Browserlist、.browserlistrc少了字母s。
配置规则核对:Browserslist 官方文档。
Syntax Transformation vs. Polyfills(语法转换与运行时补齐)
【补充:理解浏览器兼容性必须区分】
- Syntax transformation rewrites unsupported syntax. — 例如 class 转构造函数和 prototype。
- A polyfill provides a missing runtime feature. — 例如缺少的标准内置对象或方法。
- Transpiling syntax does not automatically provide every missing API.
@babel/preset-env 可按目标选择转换,也能在相应配置下配合 polyfill;不能据此认为默认补齐所有 API。Babel — preset-env
Manual Execution & Webpack Integration(命令行与集成)
Babel can run independently of Webpack.
Babel 可以从命令行处理单个文件,不要求必须经过 Webpack。(p.13)
Webpack can invoke Babel through babel-loader.
Webpack 可以通过 loader 把符合规则的源码交给 Babel。(p.14)
Configuration flow:
- Webpack 的
module.rules判断文件是否匹配。 exclude排除指定路径。use: 'babel-loader'调用 Babel。- Babel 从配置中获得 plugins / presets。
- presets 决定启用哪些转换。
2. Comparisons & Distinctions(易混淆概念对比)
| 工具 / 概念 | 主要职责 | 不能据此推断 |
|---|---|---|
| Babel | 转换源码语法 / 表示 | 自动打包整个依赖图 |
| Webpack | 模块依赖处理与打包,调用 loaders | 默认完成所有 ES / JSX 转换 |
babel-loader | Webpack 与 Babel 的桥接 | 自己决定所有目标浏览器 |
| Browserslist | 描述目标浏览器版本范围 | 自己执行源码转换 |
| Babel plugin | 单项或特定转换能力 | 必然包含完整环境兼容方案 |
| Babel preset | 一组预配置 plugins | plugins: [] 时完全没有转换 |
@babel/preset-env | 按目标环境选择 JS 转换 | 默认补齐所有 Web API |
@babel/preset-react | JSX 等 React 相关转换 | 自己负责 DOM 渲染或路由 |
| Minification | 减少输出体积 | 自动解决旧浏览器兼容性 |
| Polyfill | 补运行时缺失能力 | 自动改写浏览器无法解析的语法 |
React preset 职责核对:Babel — preset-react。
| 对比项 | Instance method | Static method |
|---|---|---|
| 课件方法 | hello() | sayHelloAll() |
| 定义位置的 ES5 示意 | Hello.prototype.hello | Hello.sayHelloAll |
| 典型调用 | hw.hello() | Hello.sayHelloAll() |
| 是否直接属于实例 | 经原型查找可用 | 不因 static 定义而成为实例方法 |
3. APIs & Configurations(API 与配置速查)
CLI(p.13)
npx babel src/client/cacher.js— 调用 Babel CLI 转译指定文件;使用可用配置时得到相应转换,默认向标准输出打印结果,不表示覆盖源文件。npx— 执行包提供的命令;它本身不是负责 class 转换的转译器。
【补充】 该命令依赖可用的 Babel CLI 与相关配置。仅命令名称本身不保证生成 ES5。
Webpack Configuration(p.14)
module: { rules: [...] }— 配置模块处理规则。test: /\.js$/— 只匹配.js后缀;$表示字符串末尾,不匹配.jsx。test: /\.jsx?$/— 修正版,同时匹配.js/.jsx;?表示x可出现零次或一次。exclude: /node_modules/— 将匹配node_modules路径的模块排除在该条 loader 规则之外;不表示这些依赖完全不参与打包。use: 'babel-loader'— 让符合条件的模块经过 Babel 处理。
Babel Configuration(p.14)
babel.config.json— 课件使用的 Babel JSON 配置文件。"plugins": []— 没有单独列出的 plugins;presets 仍可带入转换插件。"presets": ["@babel/preset-env", "@babel/preset-react"]— 同时启用环境相关转换和 React / JSX 相关转换。"@babel/preset-env"— 按目标环境选择适用的 JavaScript 转换。"@babel/preset-react"— 处理 JSX 等 React 相关语法;不等于运行 React 应用。
Target Configuration(p.12)
.browserslistrc— 正确的 Browserslist 独立配置文件名;课件少写一个s。last 3 versions— 选择每种浏览器最近三个版本,供支持 Browserslist 的工具读取。
Class / Prototype APIs(p.8)
new HelloWorld()— 创建并返回实例,执行子构造函数;示例将name初始化为'World'。super('World')— 在派生类构造函数中执行父类初始化;派生类使用this前需完成 super 调用。Hello.call(this, 'World')— 用当前this调用普通父构造函数,同步设置实例的name;函数自身未显式返回值。Object.create(Hello.prototype)— 创建一个以Hello.prototype为原型的新对象并返回;不会执行Hello构造函数。Hello.prototype.hello.call(this)— 以当前实例为this调用父类原型方法,返回问候字符串。Hello.sayHelloAll()— 调用静态方法,返回'Hello everyone!'。hw.echo()— 示例中弹出'Hello World!',返回undefined。alert(message)— 显示消息弹窗;不是异步请求 API。
Cacher / Storage / JSON(p.13)
new RegExp(/max-age=([0-9]+)/)— 创建正则对象;捕获组匹配一个或多个数字,本行不执行匹配或过期处理。localStorage.getItem('data-cache')— 同步返回已存字符串,不存在时返回null,不修改存储。JSON.parse(cache)— 同步把 JSON 文本转换为 JS 值;非法 JSON 抛SyntaxError,返回值不一定是对象。this.fetches = cache ? JSON.parse(cache) : {}— 同步修改实例属性;按字符串的 truthiness 决定是否解析,而不是验证缓存是否合法。_classCallCheck(this, Cacher)— Babel 输出中的辅助函数调用,用于检查类式构造调用;不是浏览器原生全局 API。
4. True / False Traps(判断题陷阱)
- True —
Transpilation can translate between versions of the same language.— ES2025 → ES5 就是课件例子。(p.7) - False —
A transpiler must produce assembly or machine code.— 可以输出 JS 源码。(p.3–7) - False —
Compilation and transpilation are mutually exclusive concepts.— 转译可视为源码到源码的编译。(补充) - True —
Browser compatibility is a motivation for transpiling newer JavaScript.— 新语法未被目标浏览器支持时可转换。(p.8) - False —
Babel always outputs ES5 regardless of configuration.— 输出受目标和转换配置影响。(p.12、14) - False —
Babel automatically supports every input language shown in the architecture diagram.— 示意图不等于默认 parser 能力清单。(p.11) - False —
Installing Babel guarantees that all missing browser APIs are available.— 语法转换与运行时 API 补齐不同。(p.13–14;补充) - False —
Transpilation automatically minifies the output.— 课件列为用途,不是所有配置默认执行。(p.10、14) - True —
Babel can run from the command line without Webpack.— p.13 的直接调用示例。 - False —
npx babel src/client/cacher.js necessarily overwrites cacher.js.— 示例没有指定覆盖或输出文件。(p.13) - True —
Babel can be integrated into Webpack through babel-loader.— loader 桥接两者。(p.14) - False —
The regex /\.js$/ matches both .js and .jsx files.— 只匹配.js。(p.14) - False —
Adding preset-react makes a .jsx file pass the shown /\.js$/ rule.— 规则筛选与语法转换是两个阶段。(p.14) - False —
exclude: /node_modules/ prevents all dependencies from being bundled.— 只排除该条处理规则。(p.14) - False —
An empty plugins array means no transformations when presets are configured.— presets 可包含 plugins。(p.14) - False —
Browserslist performs the transpilation itself.— 它提供目标范围。(p.12) - False —
last 3 versions selects only three browser versions in total.— 是每种浏览器最近三个版本。(p.12;修正解释) - False —
.browserlistrc is the correct configuration filename.— 正确为.browserslistrc。(p.12;课件修正) - False —
A static method is automatically available on each instance.— static 方法不属于实例原型。(p.8) - False —
Object.create(Hello.prototype) executes Hello's constructor.— 只创建指定原型的新对象。(p.8) - True —
The class example alerts "Hello World!" before "Hello everyone!".— 按调用顺序执行。(p.8) - False —
The Cacher constructor writes the cache back to localStorage.— 只展示读取与初始化。(p.13) - False —
Any nonempty data-cache value can be safely parsed as JSON.— 非空不保证 JSON 合法。(p.13) - False —
Creating a max-age regex automatically expires cached data.— 没有展示匹配、计时或清理。(p.13)
5. Exam Quick Reference(考前速查)
- Transpile: source → source;CoffeeScript → JS;ES2025 → ES5。(p.3–7)
- Babel architecture: parser → IR / AST → transformation → generation。(p.11)
- Babel ≠ Webpack: 转换源码 vs. 模块打包;桥接为
babel-loader。(p.14) - Targets: Browserslist;正确文件
.browserslistrc;last 3 versions是每种浏览器最近三版。(p.12) - CLI:
npx babel src/client/cacher.js;默认打印,不自动覆盖源文件。(p.13) - Webpack:
module.rules/test/exclude/use。(p.14) - Regex trap:
/\.js$/仅.js;/\.jsx?$/匹配.js和.jsx。(p.14) - Presets: env 管目标环境转换;react 管 JSX;
plugins: []不代表没有 preset 转换。(p.14) - Compatibility: syntax transform ≠ all runtime polyfills。
- Class: instance → prototype;static → constructor;
super()父构造;super.method()父原型方法。(p.8) - Output:
Hello World!,然后Hello everyone!。(p.8) - Cacher: 同步读存储;有真值则 parse,否则
{};无写回、无自动过期。(p.13)
Lecture 14 — Saving State
本章共 11 页。特别注意:课件对 Cookie 发送范围、Web Storage 作用域、容量和数据库存储上限有简化表述。
1. Core Concepts(核心概念)
URL State — Path, Query, Fragment(URL 保存状态)
The path, query string, and fragment can all encode application state.
路径、查询字符串和 fragment 都可以携带状态。(p.5)
【补充】Key distinctions:
- Path and query are included in requests; fragments are not.
- URL 状态便于复制、书签、分享与刷新后重建页面。
- URL 中包含数据,不代表应用会自动解析并恢复它。
- 课件 query 示例的
long=-86.7991347,15是一个参数值;其中的15不会自动成为独立 zoom 参数。 - URL 和浏览历史可暴露状态,不应将其视作秘密存储。
- Fragment 不发送给服务器,仍能被页面脚本读取,不能据此认为它保密。
Fragment 规则核对:MDN — URI fragment。
HTTP Cookies(HTTP Cookie)
Cookies store small name–value pairs managed by the browser.
Cookie 可以保存小量键值状态,客户端和服务器均有相关读写机制。(p.6–7)
课件重点:
- JavaScript 可以通过
document.cookie访问允许脚本访问的 Cookie。 - 读取多个 Cookie 后提取指定值相对麻烦,因此有库支持。
- Hard to keep confidential — 不应把普通客户端可读 Cookie 当成保密存储。
- Limited in size: about 4 KB per cookie — 课件的 4 KB 应理解为单个 Cookie 的近似容量限制,不是整个站点全部 Cookie 总共只有 4 KB。
- 符合条件的 Cookie 会随请求自动发送。
- 服务器可通过 HTTP 响应设置、更新或使 Cookie 过期。
【课件修正】“All site cookies are sent every request” is an oversimplification.(p.7)
准确表述:
Only eligible cookies are attached to a request.
Cookie 发送受 Domain、Path、Secure、SameSite、过期时间及请求凭据策略等约束。
- 不能说任意网站的全部 Cookie 都发给任意服务器。
- 服务器读到的是请求携带的 Cookie,不是任意读取整个浏览器 Cookie 仓库。
HttpOnlycookies are inaccessible to JavaScript but may still be sent with requests.Secure限定安全传输,不等于 Cookie 值自动加密,也不等于禁止 JS 访问。
document.cookie Is an Accessor(Cookie 属性的特殊读写语义)
Writing document.cookie sets one cookie; reading it returns a cookie string.
写入通常设置一个 Cookie,读取返回可见 Cookie 的字符串。(p.6)
- 连续设置
username、lat、long、zoom,不会因赋值语法就把前面不同名 Cookie 全部覆盖。 - 相同 name、domain、path 标识的 Cookie 可被更新。
- 读取形式通常为
name=value; name2=value2,不是 JS 对象。 - 读取结果不包含 HttpOnly Cookie。
- 不指定
Expires/Max-Age时通常为 session cookie;不是 sessionStorage。 - 课件正则提取的是
test2,而设置函数并未创建test2,不能把结果误认为是 username。 - 字符串
.replace()不修改浏览器中的 Cookie。
读写语义核对:MDN — Document.cookie。
Web Storage — Shared API Model(Web Storage 共用模型)
sessionStorage and localStorage expose a key–value Storage API.
二者采用相同类型的键值存储接口。(p.8–9)
【补充:代码理解必需】
- Keys and values are strings. — 数字写入后读回也是字符串。
- Operations are synchronous. —
setItem()/getItem()等不是 Promise API。 - Data is not automatically sent to the server. — 与 Cookie 的重要区别。
- 存对象通常需要 JSON 序列化,读取后再反序列化。
- Origin = scheme + host + port. — 精确作用域是 origin,不只是 domain。
- 同主机不同协议或端口通常属于不同 origin。
- 存储访问可能被策略禁止;写入可能因配额不足失败。
机制核对:MDN — Web Storage、MDN — Storage。
sessionStorage — Page-session Storage(页面会话存储)
sessionStorage persists across reloads within the same page session.
同一个页面会话中,刷新不会清除 sessionStorage。(p.8,精确作用域为补充)
- Scoped by origin and top-level browsing context. — 按 origin 与顶层标签页 / 窗口会话隔离。
- 同一标签页中,相同 origin 的页面可访问对应的 sessionStorage。
- 不同独立标签页不共享同一份可持续同步的 sessionStorage。
- The session normally ends when the tab/window closes. — 通常关闭标签页 / 窗口后结束。
- 刷新不是 session 结束。
- 跨 origin 页面无法直接读取另一 origin 的存储。
- 数据量通常远大于单个 Cookie。
【补充例外】A newly opened page may receive an initial copy from its opener.
存在 opener 时,新页面可能获得初始副本;之后两份存储独立变化。会话恢复也使“浏览器关闭必然永久清除”不适合作无条件结论。MDN — sessionStorage
localStorage — Persistent Web Storage(持久浏览器存储)
localStorage has no built-in expiration time and persists across browsing sessions.
localStorage 没有内建过期时间,通常跨刷新与浏览器会话保留。(p.9)
- Scoped by origin. — 同源页面 / 标签页通常访问同一存储区域。
- 与 sessionStorage 的主要区别是生命周期与标签页隔离方式,不是 API 形状。
- 应用可主动删除某个键,用户也可清除站点数据。
- 【课件限定】“Persists until deleted” is not an absolute durability guarantee. — 隐私模式、浏览器策略、清理等均可影响保留。
- 不能说 localStorage 会在关闭标签页时自动清除。
- localStorage 与 sessionStorage 是不同区域,相同键名可以有不同值。
- localStorage 不会自动把数据发送给服务器,也不会自动同步到另一设备。
Storage Quotas(存储容量)
课件原文:(p.8–9)
- sessionStorage:“10+ MB”。
- localStorage:“shares that 10 MB with sS”。
【课件修正】Do not treat these numbers as a universal shared-pool rule.
- MDN 将 Web Storage 概括为每 origin 总计约 10 MiB,通常 5 MiB localStorage + 5 MiB sessionStorage。
- 不能推断任何浏览器都保证 sessionStorage 单独可用 10+ MB。
- 不能把二者理解为可自由借用剩余容量的统一共享池。
- 达到配额时写入可能抛出
QuotaExceededError。 - IndexedDB 使用不同的存储管理机制,不等于也固定只有这 10 MiB。
若题目明确问 “according to the slides”,识别课件原数字;若问普遍技术事实,不应把课件数字当成无条件保证。
核对:MDN — Storage quotas and eviction criteria。
IndexedDB(索引数据库)
课件列出的特性:(p.10)
- Large-scale key–value store — 可保存较大量键值和结构化数据。
- Transactional — 通过事务组织操作。
- Structured queries — 可进行结构化查询 / 检索。
- Potentially unlimited in size — 课件强调相较简单存储更大的容量。
- More complicated API — API 更复杂。
【课件限定与补充】
- IndexedDB is not a SQL database. — “structured queries” 不表示支持 SQL。
- 支持 object stores、keys、indexes 等检索机制。
- 常用 API 主要是异步的,与同步 Web Storage 区分。
- “Potentially unlimited” 不表示真实无限;受浏览器配额、磁盘空间与清理策略限制。
核对:MDN — IndexedDB terminology。
WebSQL(Web SQL 数据库)
课件列出的特性:(p.10)
- Acts like a SQL database — 使用 SQL 数据库模型。
- Generally built upon SQLite — 通常基于 SQLite。
- Requires SQL knowledge — 需要 SQL。
- 课件同样写了 “Potentially unlimited in size”,应理解为容量描述简化。
- Deprecated — PPT 已明确标注弃用。
【补充】WebSQL is not a universally supported modern browser database.
不能把 WebSQL 与 IndexedDB 一起理解为“当前所有浏览器都支持的推荐方案”。WebSQL 已经历弃用和移除。Chrome — Deprecating and removing Web SQL
PPT 没有展示 IndexedDB / WebSQL 的具体操作 API,不需额外背一套数据库 API。
State in an SPA(SPA 中的状态)
Within a running SPA, ordinary JavaScript can hold client state.
SPA 在未刷新、未跨文档跳转时,可以用普通 JS 变量 / 对象保存运行态。(p.11)
但仍需要:
- Preserve state across reloads. — 刷新后的持久化与恢复。
- Coordinate state with the server. — 与服务器协调数据。
- Distinguish in-memory state from persistent state. — 内存保留不等于持久保存。
- Distinguish persistence from synchronization. — 写入 localStorage 不等于服务器已经得到数据。
2. Comparisons & Distinctions(易混淆概念对比)
State Mechanisms(状态保存方式)
| 机制 | 主要作用域 | 生命周期 | 自动随请求发送 | 数据形式 / 操作 |
|---|---|---|---|---|
| JS variables | 当前运行环境 | 通常随文档重建而丢失 | 否 | 任意 JS 运行态 |
| URL path / query | 当前 URL,可复制分享 | 可通过 URL 重建 | path / query 在请求中 | 应用负责编码与解析 |
| URL fragment | 当前 URL 的 fragment | 可通过 URL 重建 | 否 | 客户端解析 |
| Cookies | 按 Domain / Path 等规则 | session 或设定过期时间 | 符合条件时是 | 小量字符串键值 |
| sessionStorage | origin + 标签页会话 | 刷新保留,通常随会话结束清除 | 否 | 同步字符串键值 |
| localStorage | origin | 跨会话,无内建过期 | 否 | 同步字符串键值 |
| IndexedDB | 通常按 origin 隔离 | 持久存储,但受清理 / 配额影响 | 否 | 结构化数据、事务、主要异步 |
| WebSQL | 历史浏览器本地数据库 | 受实现与策略约束 | 否 | SQL,已弃用 |
sessionStorage vs. localStorage(p.8–9)
| 维度 | sessionStorage | localStorage |
|---|---|---|
| 共同 API | Storage API | Storage API |
| 值类型 | 字符串 | 字符串 |
| 同步 / 异步 | 同步 | 同步 |
| 刷新后 | 保留 | 保留 |
| 常规关闭标签页后 | 页面会话结束时通常清除 | 通常保留 |
| 独立标签页 | 独立存储;存在初始复制例外 | 同源标签页通常共用 |
| 跨 origin | 不共享 | 不共享 |
| 自动 HTTP 传输 | 否 | 否 |
| 内建逐项过期时间 | 无 | 无 |
| 是否与另一者共用相同键空间 | 否 | 否 |
Cookies vs. Web Storage(p.6–9)
| 维度 | Cookies | Web Storage |
|---|---|---|
| 核心优势 | 请求自动携带,便于服务器关联状态 | 方便客户端保存更多键值数据 |
| 服务器直接接收 | 符合条件时随请求到达 | 应用需主动发送 |
| 客户端读取 | document.cookie,不含 HttpOnly | getItem(key) |
| 写入语义 | 一次通常设置一个 Cookie | 按键设置值 |
| 大小 | 单 Cookie 约 4 KB | 通常为 MiB 级配额 |
| 作用域概念 | Domain / Path 等规则 | origin;sessionStorage 另加标签页会话 |
| 自动保密 | 否 | 否 |
| 标签页隔离 | 不等同于 sessionStorage | 取决于 local / session |
IndexedDB vs. WebSQL(p.10)
| 维度 | IndexedDB | WebSQL |
|---|---|---|
| 数据模型 | 结构化键值 / object stores | SQL 数据库 |
| 查询 | key / index 等,无 SQL | SQL |
| 事务 | 是,课件明确强调 | 数据库事务模型 |
| 常见 API 特性 | 主要异步,较复杂 | 需要 SQL,历史 API |
| SQLite | 不能据此认定为 SQLite 接口 | 课件说通常基于 SQLite |
| 容量 | 较大,但受配额约束 | 不能理解为真实无限 |
| 弃用状态 | 课件未标弃用 | 课件明确 Deprecated |
3. APIs & Configurations(API 与配置速查)
Cookies(p.6–7)
document.cookie = 'username=heminggs'— 设置 username Cookie;不等于覆盖所有其他 Cookie;不指定过期时间时通常是 session cookie。document.cookie = 'lat=36.1555625'— 设置 lat Cookie,值为文本。document.cookie = 'long=-86.7991347'— 设置 long Cookie。document.cookie = 'zoom=12'— 设置 zoom Cookie;读取后不会自动成为 Number。document.cookie— 同步读取当前文档可见的 Cookie 字符串;不是对象,也不包括 HttpOnly Cookie。document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, '$1')— 从 Cookie 字符串提取test2的值;未匹配时返回空字符串;同步返回新字符串,不修改 Cookie,未做 URI 解码。
课件正则的关键符号:
test2— 要寻找的 Cookie 名,不是任意变量名。([^;]*)— 捕获直到分号前的值,可以为空。'$1'— 用第一个捕获组替换整个匹配。- 找不到与“找到但值为空”都可能得到
'',不能仅凭结果区分。
【补充:理解服务器读写与生命周期所需】
Cookie: username=heminggs; zoom=12— 请求头,浏览器携带符合条件的 Cookie。Set-Cookie: username=heminggs; Path=/— 响应头,服务器要求浏览器设置 Cookie;不是直接修改服务器外任意浏览器数据。document.cookie = 'username=; Max-Age=0; Path=/'— 使匹配 name / domain / path 的 Cookie 过期;路径等范围必须与目标匹配,不能用于删除 HttpOnly Cookie。HttpOnly— 禁止脚本通过 document.cookie 访问,仍可参与 HTTP 请求。Secure— 限制安全传输。SameSite— 影响跨站请求中的 Cookie 发送。Expires/Max-Age— 控制过期时间;不要与 sessionStorage 的页面会话生命周期混为一谈。
sessionStorage(p.8)
sessionStorage.setItem('username', 'heminggs')— 同步保存键值;已有同名键则更新,返回undefined。sessionStorage.setItem('lat', 36.1555625)— 同步保存,数字转换为字符串。sessionStorage.setItem('long', -86.7991347)— 同步保存字符串形式的数值。sessionStorage.setItem('zoom', 13)— 同步保存"13",不是直接保存 Number。sessionStorage.removeItem('zoom')— 同步删除 zoom;不存在时无效果,返回undefined。sessionStorage.length— 当前存储区域的键值对数量,不是字节数,不是方法。sessionStorage.key(1)— 返回索引 1 的键名,不是值;从 0 开始,越界返回null;不要依赖固定键顺序。sessionStorage.getItem('username')— 理解所需补充:同步读取字符串,不存在返回null。
localStorage(p.9)
localStorage.setItem('username', 'heminggs')— 同步保存或覆盖同名键,无内建过期时间,返回undefined。localStorage.setItem('lat', 36.1555625)— 保存字符串形式的纬度。localStorage.setItem('long', -86.7991347)— 保存字符串形式的经度。localStorage.setItem('zoom', 13)— 保存字符串"13"。localStorage.removeItem('zoom')— 删除 zoom,不影响 sessionStorage 中的同名键。localStorage.length— 读取 localStorage 键值对数量。localStorage.key(1)— 返回第二个索引位置的键名;顺序不应当作业务保证。localStorage.getItem('username')— 同步读取值,不存在返回null;Lecture 13 p.13 也使用此方法。
【补充:对象存储与读取】
JSON.stringify(obj)— 将可序列化的 JS 值转为 JSON 文本,不修改原对象;某些输入会失败或有特殊结果。localStorage.setItem('state', JSON.stringify(obj))— 先序列化,再同步写入字符串;写入可能因配额或访问策略失败。JSON.parse(localStorage.getItem('state'))— 读取并解析 JSON;非法 JSON 抛错,实际代码应区分不存在与格式错误。Number(localStorage.getItem('zoom'))— 将读回的数值字符串转为 Number;注意不存在时Number(null) === 0,不能把它误认为已存 zoom 为 0。
Storage Example — Execution Results(p.8–9)
Assume the storage area is initially empty.
假设初始为空,执行课件函数后:
- 写入
username、lat、long、zoom,共有 4 个键。 - 删除
zoom,剩 3 个键。 console.log(storage.length)输出3。storage.getItem('zoom')返回null。storage.getItem('lat')返回"36.1555625"。storage.key(1)返回一个键名,不能仅凭写入顺序保证一定是"lat"。
如果初始存储已有其他键,length 不一定是 3。更新同名键不会额外增加一项。
console.log(value)— 输出到开发者控制台,不改变存储。alert(storage.key(1))— 弹出键名,既不读取对应值,也不删除该项。setCookies()/useSessionStorage()/useLocalStorage()— 课件自定义函数名,声明函数本身不会执行内部写入,调用后才执行。
4. True / False Traps(判断题陷阱)
Reload / SPA / URL
- True —
A reload can discard in-memory JavaScript state.— 内存变量不能当作跨刷新持久化。(p.3) - False —
Reloading always downloads every resource from the network again.— 可能使用缓存,课件重点是状态重建。(p.3;限定) - False —
SPAs no longer need persistence because they avoid page transitions.— 用户仍可能刷新或重新访问。(p.11) - True —
Ordinary JavaScript can maintain state within a running SPA.— 未重载的运行期间可保存内存状态。(p.11) - False —
Saving state locally automatically synchronizes it with the server.— 持久化与同步是不同任务。(p.11) - True —
Paths, query strings, and fragments can encode state.— 三者均可携带状态。(p.5) - False —
The server automatically receives the URL fragment.— fragment 不在 HTTP 请求中。(补充) - False —
State encoded in a URL restores the UI without application logic.— 应用仍需解析和恢复。(p.5;补充)
Cookies
- True —
Eligible cookies can be sent automatically with HTTP requests.— 这是 Cookie 与 Web Storage 的关键差别。(p.7;精确表述) - False —
Every cookie is sent with every request regardless of its destination.— 存在域、路径、安全与跨站等限制。(p.7;修正) - False —
The server can read every cookie stored in the browser.— 只能读到相应请求携带的数据。(p.7;修正) - False —
All cookies are readable through document.cookie.— HttpOnly 不可由 JS 读取。(补充) - False —
HttpOnly cookies cannot be sent to the server.— 禁止脚本访问不等于禁止 HTTP 传输。(补充) - False —
Secure means JavaScript cannot read the cookie.— Secure 与 HttpOnly 的职责不同。(补充) - False —
Assigning document.cookie replaces all existing cookies.— 通常设置一个 Cookie。(p.6) - False —
Reading document.cookie returns a JavaScript object.— 返回 Cookie 字符串。(p.6) - False —
The 4 KB limit means all cookies for a site must total less than 4 KB.— 课件数字应理解为单个 Cookie 近似限制。(p.6;限定) - False —
A cookie without an expiration time is the same mechanism as sessionStorage.— session cookie 与页面会话存储不同。(补充) - False —
The regex on slide 6 retrieves the username cookie.— 正则明确寻找test2。(p.6)
Web Storage
- True —
sessionStorage survives page reloads.— 同一页面会话刷新保留。(p.8) - False —
sessionStorage is cleared whenever the user refreshes the page.— refresh 不等于 session end。(p.8) - False —
All same-origin tabs share one live sessionStorage area.— 还按顶层标签页会话隔离。(p.8;修正) - False —
A newly opened tab must always start with empty sessionStorage.— 可能从 opener 得到初始副本。(补充) - True —
localStorage normally persists across browser sessions.— 无内建过期时间。(p.9) - False —
localStorage is guaranteed to retain data forever.— 用户清理、隐私模式或浏览器策略可影响保留。(p.9;限定) - False —
Web Storage is scoped only by hostname.— 精确作用域含协议、主机和端口。(p.8–9;修正) - False —
HTTP and HTTPS pages on the same host necessarily share localStorage.— 协议不同,origin 不同。(补充) - False —
localStorage and sessionStorage automatically send their contents to the server.— 需应用主动发送。(p.8–9;补充) - False —
setItem stores a number as a number.— 读回是字符串。(p.8–9) - False —
getItem returns undefined for a missing key.— 返回null。(补充) - False —
key(1) returns the value associated with the second key.— 返回键名。(p.8–9) - False —
length reports the number of bytes stored.— 返回键值对数量。(p.8–9) - False —
Updating an existing key always increases length.— 更新不会增加键数。(p.8–9) - False —
removeItem throws an error if the key does not exist.— 不存在时无操作。(p.8–9) - False —
Web Storage operations return Promises.— 常用 Storage API 是同步的。(补充) - False —
sessionStorage is guaranteed to provide more than 10 MB in every browser.— 课件容量不是跨浏览器保证。(p.8;修正) - False —
localStorage can always borrow any unused sessionStorage capacity.— 不应将课件描述理解成可自由借用的共享池。(p.9;修正)
Browser Databases
- True —
IndexedDB is transactional.— 课件明确特性。(p.10) - False —
IndexedDB uses SQL because it supports structured queries.— 结构化检索不等于 SQL。(p.10;限定) - False —
IndexedDB has the same synchronous key–value API as localStorage.— API、数据能力与异步机制不同。(p.10;补充) - False —
Potentially unlimited storage guarantees infinite available capacity.— 仍受配额和设备空间限制。(p.10;限定) - True —
WebSQL generally used SQLite and required SQL knowledge.— 对应课件特性。(p.10) - False —
WebSQL is a universally supported modern storage standard.— 课件已明确标注 Deprecated。(p.10)
5. Exam Quick Reference(考前速查)
- Reload: JS 内存可能丢失;缓存资源不等于保留运行态。(p.3)
- URL state: path / query / fragment;fragment 不发服务器。(p.5)
- Cookies: 小量键值;单项约 4 KB;符合规则时自动随请求发送。(p.6–7)
- Cookie getter / setter: 读字符串;写一个 Cookie;HttpOnly 不可读。(p.6)
- Cookie regex: 寻找
test2;结果''可表示缺失或空值。(p.6) - sessionStorage: origin + tab;刷新保留,通常关闭会话清除。(p.8)
- localStorage: origin;同源标签页通常共用;无内建过期。(p.9)
- Web Storage: 同步、字符串键值、不自动上传。
- Storage methods:
setItem(k,v)/getItem(k)/removeItem(k)/key(i)/.length。 - Missing key:
getItem()→null;key(i)返回键名。 - Example result: 初始为空,写 4 删 1 → length 3;已有其他键则不一定。(p.8–9)
- Quota: PPT 写 10+ MB / 共享 10 MB;准确性补充为常见 5 MiB local + 5 MiB session,不是任意共享池。(p.8–9)
- IndexedDB: 结构化键值、事务、主要异步、非 SQL、有配额。(p.10)
- WebSQL: SQL / SQLite / Deprecated。(p.10)
- SPA state: 内存状态 + 跨刷新持久化 + 服务器协调,三项都需考虑。(p.11)
Lecture 15 — Introduction to React
1. Core Concepts(核心概念)
React’s Role — View Layer(React 的职责)
React focuses on building and updating user interfaces.
React 主要处理视图层,不等于自动提供 SPA 的全部功能。(p.3–4) 裸自动react更新视图库
Virtual DOM vs. Shadow DOM(必须纠正的术语)
【课件修正】React’s Virtual DOM is not the browser’s Shadow DOM.(p.7、9、42–45)
| 名称 | 正确含义 | 与 React 的关系 |
|---|---|---|
| Virtual DOM | 用 JS 数据结构描述预期 UI,参与协调更新 | 适合理解课件所说的 React 更新机制 |
| Shadow DOM | 浏览器提供的 DOM / 样式封装机制,常见于 Web Components | React 不要求使用它才能渲染 |
| Actual DOM | 浏览器中的真实文档节点 | React DOM 最终更新的对象 |
课件把 React 的内部 UI 表示称为 “Shadow DOM”,甚至配了浏览器 Shadow DOM 图,这里术语不准确。
考试识别方式:
- 如果题目明确问课件描述,知道它想表达的是“保留 UI 表示、比较变化、更新必要 DOM”。
- 如果题目问真实技术区别,Virtual DOM ≠ Shadow DOM。
- 不要背成“React 必须创建 shadow root”。
- 不要背成“React 每次都读取整个真实 DOM,再与一份影子 DOM 逐节点比较”。
【补充】Render and commit are different phases.
- Render: React 调用组件,计算应显示的 UI。
- Commit: 将需要的修改应用到真实 DOM。
- Re-rendering does not necessarily change the DOM. — 重新执行组件不代表真实 DOM 一定变化。
- React 的协调过程不保证找到数学意义上最少的 DOM 操作。
- 浏览器最终执行 layout / paint;React 不直接接管整个浏览器绘制系统。
参考:React — Render and Commit、MDN — Shadow DOM。
DOM Performance — Reflow & Repaint(DOM 性能)
The slides emphasize reducing unnecessary DOM work.
课件性能目标是减少不必要的 DOM 操作、repaint 与 reflow。(p.6)
- Reflow / layout: 计算元素的尺寸、位置、布局。
- Repaint: 根据样式绘制像素。
- 【补充】Not every DOM change causes the same rendering cost. — 不能认为每次 DOM 修改都必然触发完整页面的 reflow 和 repaint。
- 【补充】React is not always faster than carefully written direct DOM code. — 框架有计算成本,避免“React 在任何情况下都更快”的绝对化表述。
JSX — JavaScript Syntax Extension(JSX)
JSX expresses UI using HTML-like syntax inside JavaScript.
JSX 是 JS 语法扩展,不是直接把 HTML 字符串塞进 JS。(p.8–12)
- 内置 HTML 元素使用小写标签,例如
<div>、<button>。 - 【补充】Custom component names must start with a capital letter. —
<Landing />表示组件;小写名称按内置标签处理。 {expression}用于嵌入 JS 表达式。className对应常见 HTML 的class。style接收 JS 对象,不是 CSS 字符串。- JSX 的
style={{ color: 'red' }}:外层{}进入 JS,内层{}是对象。 - 【补充】JSX is optional. — React 可以不使用 JSX;使用 JSX 时需要相应转换支持。
- 【课件限定】A component returns React-renderable values, not necessarily a real DOM node or an HTML string.
常见写法记忆:
className="foo"— CSS 类名。style={{ backgroundColor: 'red' }}— JS 样式对象,属性通常用 camelCase。<input />— JSX 中需要正确闭合标签。return (...)— 返回多行 JSX 时用括号避免换行造成意外。- 多个并列节点可用一个父节点或 Fragment 包住。
参考:React — Writing Markup with JSX。
Babel vs. React vs. React DOM(工具分工)
Babel transforms JSX; React and React DOM handle component execution and UI rendering.(p.9–10)
- Babel: 构建阶段把 JSX 转换为 JS 调用。
- React: 提供组件、状态、Hooks 等机制。
- React DOM: 将 React UI 渲染到浏览器 DOM。
- React Router: 提供客户端路由,见 p.49–58。
课件 Babel 配置:
@babel/preset-env— 目标环境相关 JS 转换。@babel/preset-react— JSX 等 React 相关转换。"plugins": []— 没有单列插件,不代表 presets 不产生转换。
【课件修正】p.9 不是严格对应的转译前后结果。
- 输入示例为 named export、
<h1>My header</h1>。 - 输出示例出现 default export、
div和"Landing Page"。 - 这些差异不是“Babel 正常转换 JSX 会自动修改文案和导出形式”的证据。
- 真正转换应保留原程序预期语义。
【补充】An explicit import React is not required by every JSX transform.
课件每个文件导入 React,但自动 JSX runtime 可以不要求为 JSX 单独导入默认 React;useState 等仍需正确导入。
Root Integration(挂载到现有页面)
A React root manages the contents of a specified DOM container.(p.10、14)
流程:
- 找到容器,例如
document.getElementById('mainDiv')。 createRoot(container)创建 root。root.render(<Landing />)请求显示组件。
【课件补全与限定】
createRoot应从react-dom/client导入。- 同一个容器通常创建一次 root,后续复用。
- 不要每次切换路由都对同一容器重新
createRoot()。 root.render()不返回渲染后的 HTML 字符串。- 不应依赖调用后下一行 DOM 就一定完成更新。
- p.10 的组件返回
"My header",右侧 DOM 示意却写"My landing page",是示例不一致,不能据此推断 React 会改变文本。 - React 管理的子树中,随意混用 jQuery 修改内容可能与 React 更新冲突。
Components & Composition(组件与组合)
A function component receives props and returns UI.(p.8、11)
A class component extends Component and defines render().(p.30–31)
- React 鼓励拆分小组件并组合。(p.13)
- 一个组件可被多次使用,每次使用具有自己的组件身份和状态。
- 模块的 named export / default export 属于 JS 模块规则,不是 React 自动互换的规则。
Children are passed through props.children.
组件标签之间的内容通过 children 传入,但子组件必须实际使用它才会显示。(p.13–15、47–48)
p.13 的代码输出陷阱:
jsx
const FancyButton = () => <button>Fancy Button</button>;
// 传入了 children,但 FancyButton 没有读取它。
<FancyButton>Go to Profile</FancyButton>实际显示:Fancy Button,不是 Go to Profile。
Props — Read-only Inputs(属性)
Props are read-only inputs from a parent to a child.(p.14–15)
- 可传字符串、数字、对象、数组、函数和 React 节点等 JS 值。
- 父组件的 state 可以作为子组件的 props。(p.16–19)
- 子组件通过回调通知父组件更新数据。
- Read-only does not mean props never change. — 父组件可以在后续渲染传入新 props。
- 【补充】Read-only does not imply deep freezing. — 对象引用并不因此自动变成深度不可变;仍不应修改传入对象。
- 自定义 prop 名称只是约定:
handleClick、clicky都不是特殊 React API。 - 对 DOM 按钮而言,真正事件属性是
onClick。
State — Component Memory(组件状态)
State stores information that React preserves between renders of the same mounted component.(p.16–20、37)
Function:
jsx
const [bars, setBars] = useState(0);Class:
jsx
this.state = { bars: 0 };
this.setState({ bars: 1 });核心判断:
- Use the setter to request an update. — 通过 setter / setState 更新。
- 不直接修改已有 state 对象或数组。
- 普通局部变量不会自动成为可持久保留的 React state。
- 同一组件后续 render 不是把
useState(0)每次都重置成 0。 - 卸载后重新挂载通常重新初始化 state。
- 组件 state 不是 localStorage,不会自动跨刷新保存。
- props、state、普通变量不应混为一谈。
【课件限定】“State contains all dynamic data” is an introductory simplification.
- 有些值可以直接从 props / state 计算,不必再存一份。
- timer ID、AbortController 等不参与 UI 的资源句柄也不必作为 state。
- 对函数组件来说,可以使用 ref 保存此类句柄;本章倒计时也可让 effect 闭包持有它们。
State Updates — Snapshot, Queue & Functional Updaters(高频代码题)
A state setter requests a future render; it does not rewrite the current render’s local state variable.
jsx
setBars(bars + 1);
console.log(bars); // 仍是当前这次 render 捕获的 barsWhen the next state depends on the previous state, use a functional updater.
jsx
setBars(prev => prev + 1);Class:
jsx
this.setState(prev => ({ bars: prev.bars + 1 }));最容易考的连续更新:
jsx
// 假设本次事件开始时 bars === 0。
setBars(bars + 1);
setBars(bars + 1);
setBars(bars + 1);
// 这三行都提交“设置为 1”,最终为 1。
setBars(prev => prev + 1);
setBars(prev => prev + 1);
setBars(prev => prev + 1);
// 如果单独从 0 开始执行这组,最终为 3。不要说“setState 是一个可以 await 的异步函数”。
- 更新会被排队,可能批处理。
- setter /
setState()不返回用于等待提交的 Promise。 - 立即读取旧变量,不代表更新失败。
- 【补充】相同值更新可能被跳过,不能保证每次 setter 调用都产生一次独立渲染或 DOM 修改。
参考:React — Queueing State Updates、React — useState。
Class State Merge vs. Hook State Replacement(表单必考)
Class setState shallowly merges the update into the current state.
jsx
// 原来 this.state = { first: 'A', last: 'B' }
this.setState({ first: 'C' });
// 结果:{ first: 'C', last: 'B' }A useState setter replaces that state value.
jsx
// 原来 form = { first: 'A', last: 'B' }
setForm({ first: 'C' });
// 结果:{ first: 'C' },last 丢失Hook 对象更新通常这样写:
jsx
setForm(prev => ({ ...prev, first: 'C' }));- 合并是浅层的,嵌套对象仍需要逐层复制。
- 不要把 class 表单的
this.setState({ [name]: value })原样替换成setForm({ [name]: value })。
参考:React — Component、React — Updating Objects in State。
Events & this Binding(事件与绑定)
Pass a function as the handler; do not invoke it during rendering.(p.15、20–23、33–36)
onClick={handleClick}— 传函数,点击时调用。onClick={() => handleClick(id)}— 传包装函数,点击时带参数调用。onClick={handleClick()}— render 时立即调用,通常不符合事件处理意图。- 【课件修正】DOM 事件属性应为
onClick,不是 p.15、20–23 的onclick。
Class methods do not automatically retain the component instance as this when used as callbacks.
课件方法:
jsx
this.clicky = this.clicky.bind(this);可选补充:
jsx
clicky = () => {
this.setState(prev => ({ bars: prev.bars + 1 }));
};- 普通 prototype 方法用作回调且依赖实例时,需要解决绑定。
- class field 箭头函数继承实例初始化时的
this,可避免手写 bind。 - 不是所有 class 方法都必须 bind。
- function component 不使用组件实例
this,通常通过闭包访问 props / state。
Component Lifecycle(组件生命周期)
课件概括为创建、挂载、渲染、更新、卸载。(p.24–29)
【课件修正】不要把列表顺序当作精确调用顺序。
典型 class 初次挂载顺序:
constructor → render → DOM commit → componentDidMount
典型更新:
props / state update → render → DOM commit → componentDidUpdate
卸载:
componentWillUnmount → 移除组件
componentDidUpdate是理解更新和完整例题所需补充,p.31 没有列出它。
| 方法 | 是否必需 | 主要作用 |
|---|---|---|
constructor(props) | 可选 | 初始化 state、绑定方法 |
render() | 必需 | 描述 UI,保持纯计算 |
componentDidMount() | 可选 | 挂载提交后启动请求、订阅、定时器等 |
componentWillUnmount() | 可选 | 清理 timer、订阅、请求等 |
static getDerivedStateFromProps(props, state) | 可选 | 在 render 前按 props/state 返回状态补丁或 null |
componentDidUpdate(prevProps, prevState) | 【补充】 | 提交更新后处理外部同步,注意条件判断 |
getDerivedStateFromProps traps:
- 是
static,不能读取实例的this。 - 返回对象或
null。 - 不只在第一次挂载执行,也可在更新时执行。
- 不适合放请求、timer 或 DOM 修改。
- 普通 props 展示通常直接读 props,不需要复制到 state。
Render should be pure.
- 不在 render 中启动请求或创建 interval。
- 不在 render 中无条件更新 state。
- render 可能重复执行,不应把“一次 render”当作“一次业务操作”。
【课件修正】p.32 的 innerText 调用错误。
jsx
document.getElementById('bar').innerText = 'I am alive!';innerText是属性,不是.innerText(...)方法。- 代码返回的 JSX 中没有展示
id="bar",所以还可能取到null。 - 卸载阶段去写一段“Goodbye”文本,不是典型的资源清理方式。
Hooks — useState & useEffect
Hooks let function components use state and synchronize with external systems.(p.16–19、41、48)
useState保存状态。useEffect处理请求、订阅、timer 等副作用。- 它们能实现 class 中某些 state / lifecycle 相关任务,但不是逐个生命周期方法的机械替换。
- 【补充】
useState/useEffect应在 function component 或自定义 Hook 顶层调用。 - 不在条件、循环、事件回调或 class 方法中调用它们。
Effect dependencies(p.41、48;细节为补充):
| 写法 | 基本行为 |
|---|---|
useEffect(setup) | 每次提交后执行 |
useEffect(setup, []) | 对该次挂载建立 effect,不因普通状态更新重跑 |
useEffect(setup, [id]) | 初始建立,后续 id 改变时清理旧 effect,再建立新 effect |
return cleanup | 依赖变化重跑前及卸载时清理 |
【课件限定】“Called once” is not an unconditional guarantee.
- p.41 的
[]可理解为常规挂载时启动一次。 - 重新挂载会再次执行。
- 开发环境启用相应 Strict Mode 检查时,可能额外执行 setup → cleanup → setup。
[]不保证整个应用生命周期只发一次请求。
Do not make the effect setup function itself async.
jsx
useEffect(() => {
async function load() {
// await ...
}
load();
return () => {
// cleanup
};
}, []);async 函数返回 Promise,而 effect setup 应返回 cleanup 函数或不返回值。
Fetching Data(请求与视图更新)
The slide pattern is: mount → fetch → parse → set state → render list.(p.40–41、48)
Class:
- 在
componentDidMount()发请求。 - 数据到达后
this.setState(...)。
Function:
- 在
useEffect()发请求。 - 数据到达后调用 setter。
Initial state matters.
- 首次 render 发生在请求完成前。
- 需要对列表初始化为
[],否则undefined.map(...)会报错。 - loading / error / empty / success 可分别渲染。
【课件修正】p.40 与 p.41 的响应结构不一致。
- p.40:
this.setState({ items: data.data }),预期 JSON 是{ data: [...] }。 - p.41、48:
setValues(data),预期 JSON 本身是[...]。 - 两者不能在不检查响应格式的情况下互换。
Fetch traps(必要补充):
fetch()返回 Promise。response.json()也返回 Promise。- HTTP 404 / 500 通常不直接让 fetch reject,需要检查
response.ok。 - 网络错误、取消请求、JSON 解析错误等需要处理。
- 请求较晚返回时可能覆盖较新的数据,需要取消或忽略旧结果。
- 跨域请求仍受 CORS 约束,React 不会绕过浏览器策略。
Lists & Keys(列表与身份)
Use map() to turn data into React elements.(p.40–45、48)
jsx
items.map(item => <ListItem key={item.id} item={item} />)Keys identify items among siblings across renders.
- 同一组兄弟节点中的 key 应唯一。
- 不要求全站唯一。
- 应在同一条数据的多次渲染中保持稳定。
- key 放在
map()直接返回的最外层元素 / 组件上。 key是 React 特殊属性,不作为普通props.key传给子组件;需要 id 时另传。- 改 key 可使 React 把它视作不同组件,重置相关状态。
- 缺 key 不一定让页面完全无法显示,但会警告并影响身份匹配。
Index keys(课件使用数组下标):
- p.44–45、48 用 index 表示 key。
- 对固定、不重排且身份不变的简单列表可以使用。
- 插入、删除、排序、有输入状态的列表优先使用稳定数据 ID。
Math.random()作为 render 时的 key 不稳定,会不断创建新身份。- p.44–45 显示的
key={I}与参数i大小写不一致;若按字面运行且没有I定义,会报错。
Forms — Controlled vs. Uncontrolled(表单)
课件术语:(p.38–39)
- Unmanaged form ≈ Uncontrolled form — 非受控输入,DOM 保存当前输入值。
- Managed form ≈ Controlled form — 受控输入,React state 决定显示值。
Controlled input loop(受控输入闭环):
state → value / checked → user input → onChange → setter → next render
最值得记的三件事:
name:这个控件对应哪个字段。value/checked:现在显示什么。onChange:输入发生后如何把数据写回 state。
Text inputs use value; checkboxes use checked.
- 文本:
event.target.value。 - checkbox:
event.target.checked。 - number input 的
.value仍是字符串,需按题意转换。 - 有
value但没有更新它的 onChange,输入通常表现为只读。 - 只初始化为空字符串
'',比初始undefined再变字符串更稳妥。 defaultValue/defaultChecked用于非受控输入的初始值。id用于 DOM 标识 / label 关联;name用于字段识别和原生 FormData,职责不同。
p.38–39 的提交限制:
- 示例外层是
<div>,按钮 click 后执行函数。 - 名为
onSubmit的普通方法,不代表浏览器自动把它当 form submit。 - 真实表单常用
<form onSubmit={handleSubmit}>,这样也能处理 Enter 提交。 - 若要客户端处理而不执行默认导航,应
event.preventDefault()。 - 表单内非提交按钮明确写
type="button"。 - React 不要求所有表单都受控。
参考:React — input。
Styling(样式方案)
CSS classes, inline styles, styled-components, and Tailwind are different styling approaches.(p.12、46–48)
Inline styles:
style={{ color: 'red' }}— JS 对象。alignItems— camelCase。gap: '1em'— 带单位字符串。
styled-components:(p.46)
- CSS-in-JS 库。
styled.div的 tagged template 创建一个 React 组件。- 可以像普通组件一样组合。
- 模板内写的是 CSS,例如
font-size,不是 JS 对象字段。 - 不是 React 内置 API。
Tailwind CSS:(p.47–48)
- utility classes,通过
className组合样式。 - 课件使用构建流程生成需要的 CSS。
- 【课件限定】“Needs to be transpiled / add to Webpack” 不表示 Tailwind 只能配 Webpack。
- Babel 的 JSX 转换不等于 Tailwind CSS 生成。
课件按钮连线陷阱:
- p.46 的
FancyButton onClick={...}要求 FancyButton 把onClick转交给实际按钮。 - 之前只读取
handleClick的实现,不能自动识别新的onClickprop。 - p.47
<TailwindButton>Profile</TailwindButton>没传 onClick,按钮文字不是导航指令。
参考:styled-components — Basics、Tailwind — PostCSS Installation。
React Router(客户端路由)
React Router maps URLs to UI and manages client-side navigation.(p.49–58)
课件 API:
BrowserRouterRoutesRouteuseParamsNavLinkuseNavigate
Route structure(p.49–50):
BrowserRouter:为子树提供浏览器路由上下文。Routes:根据当前 URL 匹配路由分支。Route path:路径模式。Route element:匹配后渲染的 React element。index:父路径上的默认页面;课件顶层例子对应/。
【课件修正】“Render all routes that match” is misleading for the shown Routes API.
- 一个
Routes通常选择最佳匹配分支。 - 嵌套路由的分支可以包含多层匹配。
- 不等于所有能匹配的兄弟 Route 全部一起渲染。
Routes外的UpTop、DownLow是普通布局,和其中哪个页面匹配是两回事。
Slide matching results(p.51–55):
| URL | 匹配 |
|---|---|
/ | index route → Landing |
/profile/graham | /profile/:id → Profile |
/profile | 不匹配需要 id 的 /profile/:id |
/login | /login → Login |
/status | /status → Status |
/profile/graham中id === 'graham'。- params 默认是字符串,不因看起来像数字就成为 Number。
- 缺少页面匹配,不代表
Routes外的布局自动消失。 - 没有 fallback Route,不会自动生成一个自定义 404 页面。
Navigation(p.58):
- Declarative:
<NavLink to="/logout">Log Out</NavLink>。 - Programmatic:
const navigate = useNavigate(); navigate('/profile/graham')。 - 链接到
/logout只表示导航;真正退出登录还需业务逻辑。 - Router Hooks 要在其支持的路由上下文中使用。
- 课件从
react-router导入;不要混用其他版本教程的旧Switch、component、useHistory写法。 - 【补充】BrowserRouter 的直接访问 / 刷新仍需服务器能正确返回 SPA 入口。
参考:React Router — Routing、React Router — Navigating。
2. Comparisons & Distinctions(易混淆概念对比)
Function vs. Class Components
| 维度 | Function component | Class component |
|---|---|---|
| 定义 | 普通函数 / 箭头函数 | extends Component |
| UI 返回 | 函数直接 return JSX | render() return JSX |
| 读 props | 参数 props 或解构 | this.props |
| 初始化 state | useState(initial) | constructor / class field 中 this.state |
| 更新 state | setValue(next) | this.setState(partial) |
| 对象更新 | 替换该 state 值,需自行保留字段 | 对顶层 state 浅合并 |
| 依赖旧值 | setN(prev => prev + 1) | this.setState(prev => ({ n: prev.n + 1 })) |
| 副作用 | useEffect | mount / update 等生命周期 |
| 清理 | effect 返回 cleanup | componentWillUnmount 等 |
| 事件中的 this | 不依赖组件实例 this | 普通方法回调可能需 bind |
| Hooks | 可在顶层使用 | 不能调用 Hooks |
| 当前支持情况 | 支持 | 仍支持,不等于已移除 |
Props vs. State vs. Ordinary Variables
| 项目 | Props | State | 普通函数局部变量 |
|---|---|---|---|
| 来源 | 父组件 | 组件自身保存 | 当前函数执行 |
| 更新方式 | 父组件传新值 | setter / setState | 普通赋值 |
| 子组件能否直接修改 | 不应修改 | 应用更新 API | 可以赋值,但不通知 React |
| 跨 render 保留 | 父组件重新提供 | 同一组件身份下保留 | 通常重新计算 |
| 修改能否自动安排 React 更新 | 父级更新间接驱动 | setter 请求更新 | 不能 |
| 跨刷新持久化 | 不自动 | 不自动 | 不自动 |
Controlled vs. Uncontrolled Forms
| 维度 | Controlled | Uncontrolled |
|---|---|---|
| 当前值由谁保存 | React state | DOM |
| 文本输入 | value + onChange | defaultValue,提交时读取 |
| checkbox | checked + onChange | defaultChecked,提交时读取 |
| 提交读取 | state 已有数据 | DOM / ref / FormData |
| 实时校验 | 容易按 state 实现 | 也能做,但需额外读取 |
| 是否必须 | 否 | 否 |
name 的作用 | 可作为更新对象的键 | FormData 字段名 |
id 的作用 | label / DOM 标识 | 同样,不等于 FormData 字段名 |
Callback vs. Immediate Invocation
| 写法 | 执行时机 / 含义 |
|---|---|
onClick={save} | 点击时调用 save |
onClick={() => save(id)} | 点击时带 id 调用 |
onClick={save()} | render 时调用 save,返回值成为 handler |
onChange={handleChange} | 输入事件发生时处理 |
handleClick={save} | 普通自定义 prop;子组件必须接线 |
onClick={props.handleClick} | 接到 DOM 按钮后才具有对应事件含义 |
Styling Approaches
| 方式 | 表达形式 | 注意 |
|---|---|---|
| CSS | className="foo" | 类对应的 CSS 需要被加载 |
| Inline | style={{ fontSize: '20pt' }} | JS 对象,camelCase |
| styled-components | styled.div`font-size: 20pt;` | 返回 React 组件,模板内是 CSS |
| Tailwind | className="flex gap-2" | utility classes,需要相应 CSS 产物 |
3. APIs & Configurations(API 与配置速查)
Imports, JSX & Root(p.8–14、30)
import React from 'react'— 课件的默认导入;自动 JSX runtime 不一定要求仅为 JSX 写它。import { Component, useState, useEffect } from 'react'— 按需导入 class 基类与 Hooks。export const Landing = props => (...)— named export,导入时通常对应import { Landing } from './landing.js'。class Landing extends Component { render() { ... } }— class 组件需实现 render;constructor 可省略。document.getElementById('mainDiv')— 返回 DOM 元素或null,不返回 React root。import { createRoot } from 'react-dom/client'— 课件 root 示例所需补全。const root = createRoot(container)— 创建管理该容器内容的 root,并返回 root 对象。root.render(<Landing name="John" />)— 请求渲染组件;props 为{ name: 'John' },不返回 HTML 字符串。root.unmount()— 【补充】卸载该 root 的组件树并执行相关清理。className="foo"— 指定 CSS 类名,不是 class 定义。style={{ color: 'red', alignItems: 'center' }}— 传入 JS 样式对象。{props.name}— 在 JSX 中插入表达式。{props.children}— 显示组件标签之间传入的内容。
State & Events(p.15–23、33–39)
const [bars, setBars] = useState(0)— 返回当前值与 setter;初始值为 0,同一组件后续 render 不反复重置。setBars(bars + 1)— 根据当前 render 的快照提交新值;不改变当前闭包中的 bars。setBars(prev => prev + 1)— 根据待处理的前一状态计算,适合累计更新与异步回调。this.state = { bars: 0 }— class 初始化状态;不要在后续业务处理中用直接赋值代替 setState。this.setState({ bars: 1 })— 排队更新并浅合并顶层字段,返回undefined。this.setState(prev => ({ bars: prev.bars + 1 }))— 依赖前值时使用的 class updater。this.setState(update, callback)— 【补充】提交完成后执行 callback;不要用await this.setState(...)等待。this.clicky = this.clicky.bind(this)— 创建绑定实例 this 的函数并保存。onClick={this.clicky}— 将函数交给点击事件,不立即调用。onClick={() => setCount(prev => prev + 1)}— 点击后累计加一。onClick={() => setCount(prev => prev - 1)}— 点击后减一,本身不限制下界。this.setState({ [ev.target.name]: ev.target.value })— class 表单通用更新;计算属性名来自 input name,其他顶层 state 字段保留。setForm(prev => ({ ...prev, [name]: value }))— Hook 对象状态的对应写法,显式保留其他字段。
Lifecycle & Effects(p.31–32、40–41、48)
constructor(props) { super(props); ... }— 初始化实例,派生类使用 this 前先调用 super。render()— 返回 UI,避免副作用;可被多次调用。componentDidMount()— 挂载提交后执行;可以发起异步任务,但 React 不等待返回的 Promise 才完成挂载。componentWillUnmount()— 卸载前清理已建立的外部资源。static getDerivedStateFromProps(props, state)— render 前返回状态补丁或 null;不能用实例 this。componentDidUpdate(prevProps, prevState)— 【补充】更新提交后执行,内部 setState / 请求需有条件以免循环。useEffect(() => { ... }, [])— 建立该次挂载的副作用;不保证开发检查与重新挂载时也只执行一次。useEffect(() => { ... }, [id])— id 改变时重新同步;先清理旧 effect。useEffect(() => { return () => cleanup(); }, [])— 注册清理逻辑,不是在 render 时立即 cleanup。document.getElementById('bar').innerText = 'I am alive!'— 正确的 DOM 属性赋值;PPT 写成函数调用有误。
Fetch & Lists(p.40–45、48)
fetch('/data')— 发起相对 URL 请求,返回Promise<Response>;默认 GET。response.json()— 异步读取并解析响应体,返回 Promise,不是直接返回最终数组。response.ok— 【补充】HTTP 状态在 200–299 时为 true。this.setState({ items: data.data })— p.40 预期响应对象里有 data 数组。setValues(data)— p.41、48 预期解析结果本身是数组。values.map(v => <li>{v}</li>)— 返回 React elements 数组;缺 key,课件后续专门修正。values.map((v, i) => <ListItem key={i}>{v}</ListItem>)— 课件 index key 写法;动态列表宜换稳定 ID。items.map(item => <ListItem key={item.id} item={item} />)— 稳定数据 ID 标识身份,key 不作为普通 prop 传入。const ListItem = ({ children }) => <li>{children}</li>— 使用 children 渲染父组件传入内容。
Forms(p.38–39,含必要补充)
document.getElementById('first_name').value— 同步读 DOM 当前输入字符串;元素不存在会因访问 null 报错。<input name="first" value={first} onChange={handleChange} />— 受控文本输入,state 是显示值来源。event.target.name— 发生事件的控件字段名。event.target.value— 当前控件的字符串值。event.target.checked— checkbox / radio 的布尔选中状态。<input type="checkbox" checked={agree} onChange={handleChange} />— 受控 checkbox。<input defaultValue="John" />— 非受控输入的初始值,不是后续受控 value。<form onSubmit={handleSubmit}>— 处理实际 form 提交,支持常规按钮和 Enter 提交。event.preventDefault()— 阻止默认提交导航,不自动发请求,也不阻止事件冒泡。<button type="submit">Save</button>— 提交按钮。<button type="button">Cancel</button>— 普通按钮,避免误触发表单提交。new FormData(event.currentTarget)— 【扩展】从正在提交的 form 提取成功控件;依赖 name,不依赖 id。formData.get('first')— 【扩展】读取字段,缺失返回 null;文件字段可能返回 File。
styled-components & Tailwind(p.46–48)
import styled from 'styled-components'— 导入第三方 CSS-in-JS 工具。const Clicker = styled.div`color: red; font-size: 20pt;`;— 创建带样式的 div React 组件。<Clicker>{count}</Clicker>— 组合样式组件并传 children。className="text-red-500 bg-blue-900"— 红色文字、深蓝背景。className="p-1 pl-2 pr-2"— 内边距,并单独设置左右内边距。className="rounded-xl border-2 border-amber-200"— 圆角、边框宽度、边框颜色。className="m-2 flex flex-row items-center gap-2"— 外边距、flex 横向布局、交叉轴居中、间距。className="m-4"— 外边距。className="text-green-600"— 绿色文字。className="flex flex-col"— 纵向 flex。className="list-disc"— 圆点列表样式。
数字 spacing 类对应主题的间距刻度,不要把
m-2背成固定 2px。
React Router(p.49–58)
import { BrowserRouter, Routes, Route } from 'react-router'— 课件路由组件导入方式,实际项目与安装版本一致。<BrowserRouter>...</BrowserRouter>— 建立浏览器路由上下文。<Routes>...</Routes>— 按当前 URL 选择匹配分支。<Route index element={<Landing />} />— 当前父路径的默认页面。<Route path="/profile/:id" element={<Profile foo="bar" />} />— 匹配动态 id;额外传入普通 prop foo。<Route path="/login" element={<Login />} />— 固定路径。<Route path="/status" element={<Status />} />— 固定路径。<Route path="/landing" element={<Landing />} />— path 决定匹配,element 决定 UI。const { id } = useParams()— 读取匹配的路径参数;不会自动转数字。<NavLink to="/logout">Log Out</NavLink>— 声明式导航;文字不是退出登录的业务实现。const navigate = useNavigate()— 获取导航函数,Hook 调用本身不跳转。navigate(`/profile/${username}`)— 程序式导航,默认通常新增历史项。<Route path="*" element={<NotFound />} />— 【补充】兜底页面;课件没有展示,但不能假定它自动存在。
4. True / False Traps(判断题陷阱)
React / DOM / JSX
- True —
React primarily focuses on the view layer.— 不自动包办 SPA 所有职责。(p.4) - False —
React requires the browser's Shadow DOM to render components.— Virtual DOM 与 Shadow DOM 不同。(p.7;修正) - False —
Every re-render replaces the entire real DOM subtree.— 计算 UI 与提交 DOM 不同。(p.6–7;补充) - False —
React always produces the smallest possible set of DOM operations.— 不能作数学最优保证。(补充) - False —
Every DOM mutation forces a full-page reflow and repaint.— 代价取决于修改内容。(p.6;限定) - False —
JSX is an HTML string.— JSX 转为 JS 表达式 / 调用。(p.8–9) - False —
JSX is required to use React.— 可不用 JSX。(补充) - False —
Babel is responsible for updating the DOM after a click.— Babel 转换代码,运行时由 React / React DOM 等执行。(p.9–10) - False —
Inline styles use the same string syntax as an HTML style attribute.— React style 接收对象。(p.12) - False —
A component must display any children passed to it.— 子组件需实际渲染 children。(p.13) - False —
createRoot automatically renders a component.— 仍需 root.render。(p.10) - False —
A new root should be created on the same container for every route change.— 通常创建后复用。(p.10;限定)
Props / State / Events
- True —
Functions can be passed through props.— 回调也是 JS 值。(p.15) - False —
Read-only props can never change over time.— 父组件可传入新 props。(p.14) - True —
A parent's state can be passed to a child as props.— 状态所有权与子组件接收方式不同。(p.16) - False —
useState(0) resets the state to zero on every render.— 初始值不反复重置。(p.16–19) - False —
Changing an ordinary local variable automatically re-renders the component.— 需 React 更新机制。(补充) - False —
Calling a setter immediately changes the current closure's state variable.— 当前 render 的快照不变。(补充) - False —
Every setter call produces one separate DOM update.— 可能批处理或跳过相同值更新。(补充) - False —
await setState(...) waits for the DOM update.— setState 不返回该类 Promise。(补充) - False —
A useState object setter merges fields just like class setState.— Hook 替换,class 顶层浅合并。(p.37、39;补充) - False —
Directly mutating a state object is the recommended way to update React UI.— 应创建新值再提交。(补充) - False —
onclick is the correct JSX prop for a DOM button click handler.— 应写 onClick。(p.15、20–23;修正) - False —
onClick={save()} calls save only after a click.— render 时已调用。(补充) - False —
Every custom prop named handleClick automatically becomes a DOM event.— 子组件需转发。(p.15) - False —
All class methods must be manually bound.— 需根据使用方式;class field 箭头函数可避免手动绑定。(p.33–36) - False —
A class render method reads props through a built-in local variable named props.— 通常是 this.props。(p.33–37;修正)
Lifecycle / Effects / Fetch
- True —
render is required for a class component; constructor is optional.— 课件明确。(p.31) - False —
componentDidMount runs before the initial render.— 初次 render / commit 后执行。(p.24–31;修正) - False —
render is a suitable place to start a recurring timer.— render 应保持纯计算。(补充) - True —
componentWillUnmount is a place to clean up timers and subscriptions.— 对称清理。(p.31–32;补充) - False —
getDerivedStateFromProps can access the component instance through this.— static 方法。(p.31) - False —
useState and useEffect can be called inside class render methods.— 不符合这些 Hooks 的调用规则。(补充) - False —
useEffect(..., []) is guaranteed to execute exactly once forever.— 重新挂载、开发检查等均是例外。(p.41;限定) - False —
An effect cleanup runs only when the component unmounts.— 依赖变化重跑前也会执行。(补充) - False —
An async effect setup returns a cleanup function automatically.— async 返回 Promise。(补充) - False —
fetch rejects automatically whenever the server returns HTTP 404.— 需检查 response.ok。(p.40–41;补充) - False —
response.json() returns the parsed array synchronously.— 返回 Promise。(p.40–41) - False —
The first render waits for componentDidMount's fetch to finish.— 首次 render 在前,数据随后更新。(p.40) - False —
The responses expected by slides 40 and 41 have identical shapes.— data.data 与 data 不同。(p.40–41)
Lists / Forms / Styles / Router
- True —
Keys should be unique among siblings.— 不要求全站唯一。(p.42–45) - False —
The array index is always a safe key.— 动态列表可能错配身份。(p.44–45、48;限定) - False —
A key placed only inside ListItem identifies the outer mapped ListItem elements.— key 应放在 map 直接返回的元素上。(p.42–45) - False —
A component can read its key through props.key.— 特殊属性不按普通 prop 传递。(补充) - False —
A different random key on each render improves component reuse.— 会破坏稳定身份。(补充) - False —
All React inputs must be controlled.— 课件同时展示非受控方案。(p.38–39) - False —
A controlled checkbox should be driven by value instead of checked.— 选中状态使用 checked。(补充) - False —
An input of type number returns a Number from event.target.value.— value 仍是字符串。(补充) - False —
id and name serve exactly the same purpose in forms.— 标识 / label 与字段名不同。(p.38–39;补充) - False —
A method named onSubmit automatically prevents browser form navigation.— 名称没有此效果,需绑定并 preventDefault。(p.38–39;补充) - False —
styled-components is built into React.— 第三方库。(p.46) - False —
Tailwind can only be used with Webpack.— 课件构建方式不等于唯一方式。(p.47;限定) - False —
Every matching sibling Route inside one Routes is rendered simultaneously.— 通常选择最佳匹配分支。(p.50–55;修正) - True —
/profile/graham matches /profile/:id.— id 是 graham。(p.53–54) - False —
/profile matches /profile/:id without an id segment.— 本例 id 必需。(p.55) - False —
Unmatched URLs automatically remove components outside Routes.— 外部布局仍可显示。(p.50–55) - False —
Navigating to /logout automatically implements logout.— 路由不等于认证业务。(p.58)
5. Exam Quick Reference(考前速查)
- React = view layer;Router / fetch / persistence 另行配合。(p.3–4)
- Virtual DOM ≠ Shadow DOM;PPT 名称混用。(p.7)
- Render ≠ commit;组件重跑不一定修改真实 DOM。
- Babel → JSX 转 JS;React DOM → 浏览器 DOM。(p.9–10)
- Root:
createRoot(container)→root.render(<App />);同容器复用 root。 - JSX:
className、onClick、style={{...}}、{expression}。 - Children: 传入 ≠ 自动显示,需
{children}。(p.13) - Props: 只读输入,可含函数;父级可传新 props。(p.14–15)
- Function: 参数 props,
useState,setter,useEffect。 - Class:
this.props、this.state、this.setState、render。 - State: 当前 render 是快照;依赖前值用 updater。
- Merge: class setState 浅合并;Hook setter 替换整个对应值。
- Event: 传函数,不在 JSX 中立即执行;class 注意 this。
- Mount order: constructor → render → commit → componentDidMount。
- Effect:
[]挂载;[id]依赖变化;cleanup 先于重建,也用于卸载。 - Fetch: Promise → 检查 ok → json Promise → setter;首屏先有空数组。
- Response shape: p.40
{data: []};p.41 / 48[]。 - List: map + stable sibling key;index 非万能;key 不在 props 中。
- Form: 文本 value,checkbox checked,name 选字段,onChange 回写。
- Submit: form onSubmit → preventDefault → validate → 处理数据。
- Router: BrowserRouter → Routes → Route;path 匹配,element 渲染。
- Params:
useParams();/profile/:id需要 id。 - Navigate: NavLink / useNavigate;不是旧版 useHistory。
6. Programming Playbook(编程题:按什么顺序写)
以下为【编程题扩展】。目标是看见题目后快速恢复写业务代码的手感,不要求把这些防御处理全部机械背诵。
6.1 读题后先列这五件事
- UI state — 哪些值变化后要更新界面:数据、loading、error、输入值。
- Inputs — 哪些是父组件传入的 props:endpoint、初始参数、回调。
- Side effects — 哪些要请求、计时、订阅。
- Cleanup — 离开页面 / 参数变化 / 重试时,要清掉什么。
- Rendering branches — loading、error、empty、success 怎么显示。
Class 版落点:
- constructor:初始化 state、绑定普通方法、保存资源句柄。
- componentDidMount:启动。
- componentDidUpdate:props 变化时重新启动,必须写条件。
- componentWillUnmount:清理。
- render:只算 UI。
Function 版落点:
- useState:UI 数据。
- useEffect:启动外部工作,并返回 cleanup。
- dependency array:什么变化后重做。
- 事件函数:处理用户操作。
- return JSX:显示结果。
6.2 完整例题:从 API 读取倒计时,支持重新获取
6.3 Class Version(完整 class 组件)
jsx
import React, { Component } from 'react';
export default class CountdownClass extends Component {
constructor(props) {
super(props);
// 1. 只有这些数据直接决定 UI,放在 state。
this.state = {
remaining: 0,
loading: true,
error: '',
};
// 2. 这些是外部资源 / 计算辅助值,不需要显示到界面。
// 保存成实例字段,变化时不需要触发 render。
this.timerId = null;
this.controller = null;
this.deadline = 0;
// 3. 普通方法将被作为回调传出,需要保住 this。
// tick 会交给 setInterval,load 会交给按钮。
this.tick = this.tick.bind(this);
this.load = this.load.bind(this);
}
componentDidMount() {
// 首次 render 和 DOM 提交之后启动请求。
this.load();
}
componentDidUpdate(prevProps) {
// 父组件换 endpoint 时重新取数。
// 必须判断变化,否则下面的 setState 又触发 didUpdate,
// 再请求、再 setState,就可能形成循环。
if (prevProps.endpoint !== this.props.endpoint) {
this.load();
}
}
componentWillUnmount() {
// 离开页面时,timer 和未完成请求都要清理。
this.clearResources();
}
clearResources() {
if (this.timerId !== null) {
clearInterval(this.timerId);
this.timerId = null;
}
if (this.controller !== null) {
this.controller.abort();
this.controller = null;
}
}
tick() {
// 不依赖 this.state.remaining 的旧值。
// 即使回调晚了,也按当前时间重新算。
const remaining = Math.max(
0,
Math.ceil((this.deadline - Date.now()) / 1000)
);
this.setState({ remaining });
if (remaining === 0 && this.timerId !== null) {
clearInterval(this.timerId);
this.timerId = null;
}
}
async load() {
// 重试或 endpoint 改变时,先清上一轮。
this.clearResources();
// 每一轮请求使用自己的 controller。
const controller = new AbortController();
this.controller = controller;
this.setState({
loading: true,
error: '',
remaining: 0,
});
const endpoint = this.props.endpoint ?? '/api/countdown';
try {
const response = await fetch(endpoint, {
signal: controller.signal,
});
// fetch 遇到 HTTP 500 并不自动进入 catch。
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
// 该轮请求可能已因卸载、重试或参数变化而取消。
// 不让过期结果继续写 state 或创建 timer。
if (controller.signal.aborted) return;
// 按本题约定验证响应结构。
if (
!Number.isSafeInteger(data.seconds) ||
data.seconds < 0
) {
throw new Error('seconds 必须是非负整数');
}
// 本题定义:从收到响应后开始倒计时。
this.deadline = Date.now() + data.seconds * 1000;
// class setState 浅合并这些字段。
this.setState({
remaining: data.seconds,
loading: false,
error: '',
});
// 0 秒不创建 timer,直接显示结束。
if (data.seconds > 0) {
// 250ms 是刷新显示的检查间隔,不是每次减 0.25。
this.timerId = setInterval(this.tick, 250);
}
} catch (error) {
// 主动取消不是需要展示给用户的业务失败。
if (controller.signal.aborted) return;
this.setState({
loading: false,
error: error instanceof Error ? error.message : String(error),
});
}
}
render() {
const { remaining, loading, error } = this.state;
// 派生显示值:直接算即可,不必再存 minutes / seconds 两份 state。
const minutes = Math.floor(remaining / 60);
const seconds = String(remaining % 60).padStart(2, '0');
return (
<section>
<h2>{this.props.title ?? 'Countdown'}</h2>
{loading ? (
<p>正在读取倒计时……</p>
) : error ? (
<p role="alert">读取失败:{error}</p>
) : (
<>
<p>剩余时间:{minutes}:{seconds}</p>
{remaining === 0 && <p>时间到!</p>}
</>
)}
{/* 传函数,不写 onClick={this.load()}。 */}
<button
type="button"
onClick={this.load}
disabled={loading}
>
{loading ? '读取中……' : '重新获取 / 重试'}
</button>
</section>
);
}
}调用:
jsx
<CountdownClass endpoint="/api/countdown" title="考试剩余时间" />这题主要得分点:
super(props)、state 初始化、普通方法绑定。- 挂载请求、更新 state、render 读
this.state。 - endpoint 变化时有条件重新请求。
- 失败分支。
- timer 在 0 停止。
- 卸载清理与旧请求取消。
- render 中没有创建 timer 或 fetch。
6.4 Function Version(完整 function 组件)
jsx
import React, { useEffect, useState } from 'react';
export default function CountdownFunction({
endpoint = '/api/countdown',
title = 'Countdown',
}) {
// 1. UI state。
const [remaining, setRemaining] = useState(0);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
// 2. 用一个递增值表示“用户要求重新加载”。
// 它放进 effect 依赖,改变后会先清理旧工作,再启动新工作。
const [reloadKey, setReloadKey] = useState(0);
useEffect(() => {
// 这一轮 effect 的资源由这一轮闭包持有。
// 不会因组件后续 render 就自动丢失。
const controller = new AbortController();
let timerId = null;
async function load() {
setLoading(true);
setError('');
setRemaining(0);
try {
const response = await fetch(endpoint, {
signal: controller.signal,
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
// cleanup 已执行时,不让这一轮旧结果更新 UI。
if (controller.signal.aborted) return;
if (
!Number.isSafeInteger(data.seconds) ||
data.seconds < 0
) {
throw new Error('seconds 必须是非负整数');
}
const deadline = Date.now() + data.seconds * 1000;
setRemaining(data.seconds);
setLoading(false);
if (data.seconds > 0) {
timerId = setInterval(() => {
// 这里不读闭包里的 remaining,也不依赖 remaining - 1。
// 使用本轮固定的截止时间,避免 stale closure 问题。
const nextRemaining = Math.max(
0,
Math.ceil((deadline - Date.now()) / 1000)
);
setRemaining(nextRemaining);
if (nextRemaining === 0) {
clearInterval(timerId);
timerId = null;
}
}, 250);
}
} catch (error) {
if (controller.signal.aborted) return;
setError(
error instanceof Error ? error.message : String(error)
);
setLoading(false);
}
}
// effect setup 本身不是 async,内部函数才是。
load();
// 3. endpoint / reloadKey 改变前,或组件卸载时执行。
return () => {
controller.abort();
if (timerId !== null) {
clearInterval(timerId);
}
};
}, [endpoint, reloadKey]);
const minutes = Math.floor(remaining / 60);
const seconds = String(remaining % 60).padStart(2, '0');
return (
<section>
<h2>{title}</h2>
{loading ? (
<p>正在读取倒计时……</p>
) : error ? (
<p role="alert">读取失败:{error}</p>
) : (
<>
<p>剩余时间:{minutes}:{seconds}</p>
{remaining === 0 && <p>时间到!</p>}
</>
)}
<button
type="button"
disabled={loading}
onClick={() => setReloadKey(prev => prev + 1)}
>
{loading ? '读取中……' : '重新获取 / 重试'}
</button>
</section>
);
}调用:
jsx
<CountdownFunction endpoint="/api/countdown" title="考试剩余时间" />Function 版最容易写错的地方:
- 不要
useEffect(async () => {...}, [])。 - endpoint 在 effect 中使用,所以依赖中要有 endpoint。
- 不把 remaining 放进这个取数 effect 的依赖,否则每次倒计时变化都重新请求。
- cleanup 清理的是该轮 effect 建立的资源。
- 不在 render 函数体直接
setInterval()。 - timer ID 不决定 UI,无需专门放 state。
如果题目只考最简单的“每秒减一”:
jsx
useEffect(() => {
const id = setInterval(() => {
// 用 updater,避免闭包一直读取第一次 render 的 count。
setCount(prev => Math.max(0, prev - 1));
}, 1000);
return () => clearInterval(id);
}, []);这段会在 0 后继续保留 interval,直到卸载;完整题要求到 0 停止时,还需补停止逻辑。它也没有截止时间版本的延迟修正能力。
6.5 倒计时扩展 API 速查
new AbortController()— 创建请求取消控制器。fetch(url, { signal: controller.signal })— 将请求与取消信号关联。controller.abort()— 请求取消;异步代码仍需避免使用已失效结果。controller.signal.aborted— 检查本轮是否已取消。setInterval(callback, 250)— 安排重复回调并返回 timer ID;不保证严格每 250ms 准点执行。clearInterval(id)— 停止后续 interval 回调。Date.now()— 返回当前时间戳,单位毫秒。Math.ceil(ms / 1000)— 将正的剩余毫秒向上取整为秒。Math.max(0, seconds)— 防止显示负数。Math.floor(seconds / 60)— 计算分钟数。String(seconds % 60).padStart(2, '0')— 秒数格式化为两位。Number.isSafeInteger(value)— 验证是否为安全整数,不会把字符串自动转成数字。
6.6 List Example(小例子:列表、完成状态、删除与排序)
Possible exam prompt:
Render a task list. Allow toggling completion, deleting a task, and reversing the order. Preserve each item's identity.
先 state 数组 → map 渲染 → key 用 id → 更新用新数组。
jsx
import React, { useState } from 'react';
function TaskRow({ task, onToggle, onRemove }) {
return (
<li>
<label>
<input
type="checkbox"
checked={task.done}
onChange={() => onToggle(task.id)}
/>
<span
style={{
textDecoration: task.done ? 'line-through' : 'none',
}}
>
{task.title}
</span>
</label>
<button
type="button"
onClick={() => onRemove(task.id)}
>
删除
</button>
</li>
);
}
export default function TaskList() {
const [tasks, setTasks] = useState([
{ id: 'a', title: 'Review props and state', done: false },
{ id: 'b', title: 'Review forms', done: false },
{ id: 'c', title: 'Review routing', done: true },
]);
function toggleTask(id) {
setTasks(prev =>
prev.map(task =>
task.id === id
// 新建被修改的对象,不直接 task.done = ...
? { ...task, done: !task.done }
: task
)
);
}
function removeTask(id) {
// filter 返回新数组。
setTasks(prev => prev.filter(task => task.id !== id));
}
function reverseTasks() {
// reverse 会修改数组,所以先复制再 reverse。
setTasks(prev => [...prev].reverse());
}
// 派生值直接算,不另外维护一个容易不同步的 completedCount state。
const completedCount = tasks.filter(task => task.done).length;
return (
<section>
<p>已完成 {completedCount} / {tasks.length}</p>
<button type="button" onClick={reverseTasks}>
倒序
</button>
{tasks.length === 0 ? (
<p>没有任务</p>
) : (
<ul>
{tasks.map(task => (
<TaskRow
// key 必须在 map 直接返回的 TaskRow 上。
// 删除或倒序后,task.id 仍代表同一条数据。
key={task.id}
// key 不会作为 props.key 传入,所以另传 task。
task={task}
onToggle={toggleTask}
onRemove={removeTask}
/>
))}
</ul>
)}
</section>
);
}List 题目快速替换模板:
- 新增:
setItems(prev => [...prev, newItem])。 - 删除:
setItems(prev => prev.filter(item => item.id !== id))。 - 更新:
setItems(prev => prev.map(item => item.id === id ? { ...item, ...patch } : item))。 - 排序:
setItems(prev => [...prev].sort(compare))。 - 数组 callback 使用
{ ... }函数体时别忘return:
jsx
// 错:每一项回调都返回 undefined。
items.map(item => {
<li key={item.id}>{item.title}</li>;
});
// 对:显式 return。
items.map(item => {
return <li key={item.id}>{item.title}</li>;
});数组更新参考:React — Updating Arrays in State。
6.7 Form Example(完整受控表单:先找字段,再更新字段)
Possible exam prompt:
Build a form with first name, last name, age, and a subscription checkbox. Validate on submit and display the submitted data.
不要把 form 想复杂:它就是“一个对象 + 几个输入框 + 一个通用更新函数”。
| 代码 | 干什么 |
|---|---|
form.first | state 中这个字段的当前值 |
name="first" | 告诉通用 handler 这次改的是 first |
value={form.first} | 输入框显示 state 的值 |
onChange={handleChange} | 用户输入后回写 state |
[name]: nextValue | 根据字段名更新对应属性 |
...prev | 保留其他字段 |
onSubmit | 拿整份 state 做校验 / 保存 |
jsx
import React, { useState } from 'react';
const EMPTY_FORM = {
first: '',
last: '',
age: '', // 输入过程中保留字符串,允许用户暂时清空。
subscribe: false,
};
export default function ProfileForm() {
const [form, setForm] = useState({ ...EMPTY_FORM });
const [error, setError] = useState('');
const [submitted, setSubmitted] = useState(null);
function handleChange(event) {
// 在事件处理时先读出需要的值。
const { name, type, value, checked } = event.target;
// checkbox 要 checked,文本 / number 输入取 value。
const nextValue = type === 'checkbox' ? checked : value;
setForm(prev => ({
...prev, // Hook 不自动合并,必须保留其他字段。
[name]: nextValue, // 例如 name === 'first',就更新 first。
}));
// 用户重新修改后,清除旧错误提示。
setError('');
}
function handleSubmit(event) {
// form 默认提交可能导航 / 刷新,这里交给 JS 处理。
event.preventDefault();
const first = form.first.trim();
const last = form.last.trim();
if (!first || !last) {
setError('First name 和 last name 不能为空');
return;
}
// 空字符串单独判断,避免 Number('') === 0 被误当成用户输入了 0。
if (form.age.trim() === '') {
setError('请输入年龄');
return;
}
const age = Number(form.age);
if (!Number.isInteger(age) || age < 0 || age > 150) {
setError('年龄必须是 0 到 150 之间的整数');
return;
}
// 提交时构造业务 payload。
// 输入态 age 是字符串,提交态 age 是 number。
const payload = {
first,
last,
age,
subscribe: form.subscribe,
};
// 本例只把提交结果展示出来,没有自动向服务器发送。
// 若题目要求保存 API,把这里替换 / 扩展为 fetch POST。
setSubmitted(payload);
setError('');
}
function resetForm() {
// 受控输入由 state 决定,重置 state 就能重置输入框。
setForm({ ...EMPTY_FORM });
setError('');
setSubmitted(null);
}
return (
// noValidate:本例统一展示自己写的校验错误。
<form onSubmit={handleSubmit} noValidate>
<div>
<label htmlFor="profile-first">First name</label>
<input
id="profile-first"
name="first"
value={form.first}
onChange={handleChange}
/>
</div>
<div>
<label htmlFor="profile-last">Last name</label>
<input
id="profile-last"
name="last"
value={form.last}
onChange={handleChange}
/>
</div>
<div>
<label htmlFor="profile-age">Age</label>
<input
id="profile-age"
name="age"
type="number"
min="0"
max="150"
step="1"
value={form.age}
onChange={handleChange}
/>
</div>
<label>
<input
name="subscribe"
type="checkbox"
checked={form.subscribe}
onChange={handleChange}
/>
接收通知
</label>
{error && <p role="alert">{error}</p>}
<div>
<button type="submit">提交</button>
{/* 显式 type="button",否则可能触发表单提交。 */}
<button type="button" onClick={resetForm}>
重置
</button>
</div>
{submitted !== null && (
<pre>{JSON.stringify(submitted, null, 2)}</pre>
)}
</form>
);
}Form 执行过程,用一句业务话记忆:
用户改输入框 → event.target.name 找到字段 → .value / .checked 得到值 → setter 合并回对象 → React 用新 state 重画输入框。
改成 class 时,核心差别只有这些:
jsx
class ProfileFormClass extends React.Component {
constructor(props) {
super(props);
this.state = {
first: '',
last: '',
age: '',
subscribe: false,
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
const { name, type, value, checked } = event.target;
// class setState 顶层浅合并,所以这里不必 ...this.state。
this.setState({
[name]: type === 'checkbox' ? checked : value,
});
}
handleSubmit(event) {
event.preventDefault();
// 正式题目按需要在此 trim / Number / 校验 / fetch。
console.log(this.state);
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input
name="first"
value={this.state.first}
onChange={this.handleChange}
/>
<input
name="last"
value={this.state.last}
onChange={this.handleChange}
/>
<input
name="age"
type="number"
value={this.state.age}
onChange={this.handleChange}
/>
<input
name="subscribe"
type="checkbox"
checked={this.state.subscribe}
onChange={this.handleChange}
/>
<button type="submit">提交</button>
</form>
);
}
}6.8 Uncontrolled Form(更短:只在提交时收集)
如果题目不要求逐字校验、联动显示、输入时计算等功能,非受控表单可以很短。
jsx
import React, { useState } from 'react';
export default function UncontrolledProfileForm() {
const [result, setResult] = useState(null);
function handleSubmit(event) {
event.preventDefault();
// currentTarget 是绑定 onSubmit 的 form。
// 使用 name 收集字段,不需要逐个 getElementById。
const data = new FormData(event.currentTarget);
setResult({
first: String(data.get('first') ?? '').trim(),
last: String(data.get('last') ?? '').trim(),
// 未勾选的 checkbox 通常不进入 FormData。
subscribe: data.has('subscribe'),
});
}
return (
<form onSubmit={handleSubmit}>
{/* 没有 value + onChange,DOM 保存用户当前输入。 */}
<input name="first" defaultValue="John" />
<input name="last" defaultValue="" />
<label>
<input
type="checkbox"
name="subscribe"
defaultChecked={false}
/>
接收通知
</label>
<button type="submit">提交</button>
{/* 原生 reset 对非受控输入恢复默认值,不会自动清掉 result state。 */}
<button type="reset">恢复输入默认值</button>
{result && <pre>{JSON.stringify(result, null, 2)}</pre>}
</form>
);
}受控 / 非受控最后记这两句:
- Controlled: 我每次都让 state 决定输入框显示什么。
- Uncontrolled: 用户先在 DOM 里输入,我提交时再把值收上来。
6.9 Router Mini Example(路径参数 + 列表跳转)
jsx
import React from 'react';
import {
BrowserRouter,
Routes,
Route,
NavLink,
useNavigate,
useParams,
} from 'react-router';
function Home() {
const navigate = useNavigate();
return (
<button
type="button"
onClick={() => navigate('/profile/graham')}
>
查看 Graham
</button>
);
}
function Profile() {
// /profile/graham → id === 'graham'
const { id } = useParams();
return <h1>Profile: {id}</h1>;
}
export default function App() {
return (
<BrowserRouter>
{/* 位于 Routes 外,页面切换时仍显示。 */}
<nav>
<NavLink to="/">首页</NavLink>
</nav>
<Routes>
<Route index element={<Home />} />
<Route path="/profile/:id" element={<Profile />} />
<Route path="*" element={<p>页面不存在</p>} />
</Routes>
</BrowserRouter>
);
}路由题写法顺序:
- 最外面包 Router。
- Routes 里声明 path / element。
:id表示动态段,页面中useParams()读取。- 用户点击链接用 NavLink。
- 保存成功等业务动作后跳转用
navigate(...)。 - 刷新子路径报服务器 404,要检查服务器 SPA fallback,不是给组件再加一个 useEffect。
Lecture 18 — Introduction to Node.js
本章共 20 页,页码包含标题页。已检查文字、截图及图示。
【课件修正】:修正课件中的简化或错误表述。【补充】:用于准确判断代码行为的必要知识。人物经历、组织历史与重复背景页不作记忆重点。
1. Core Concepts(核心概念)
Node.js Architecture(运行时架构)
Node.js combines the V8 JavaScript engine with libuv and system-level APIs.
Node.js 将 V8、libuv 事件循环与底层系统 API 组合为浏览器外的 JavaScript 运行环境。(p.3–7)
- V8 executes JavaScript. — V8 负责执行 JavaScript。
- libuv supports the event loop and asynchronous I/O infrastructure. — libuv 提供事件循环及异步 I/O 基础设施。
- Node.js exposes operating-system capabilities. — 可以访问文件系统、网络、进程等系统能力。
- Node.js is a runtime, not a web framework. — Express 是框架,Node.js 是运行时。
- Node.js is not limited to HTTP servers. — 也能写 TCP 服务、命令行程序、文件处理等。(p.13–14)
- 课件关于 Chakra / 引擎独立性的旧规划已经划线,不能背成当前标准 Node.js 可随意切换 JS 引擎。(p.3–7)
Single Thread vs. Concurrency(单线程与并发)
JavaScript callbacks on a Node.js event loop normally execute one at a time.
同一个事件循环中的普通 JS 回调通常逐个执行。(p.11)
【课件限定】“Node.js is single-threaded” does not mean the entire process has only one thread.
- 主线程执行 JS,不代表底层 I/O、线程池、Worker 都只占同一个线程。
- 异步 I/O 可使多个请求的等待过程重叠。
- Concurrency does not require one JavaScript thread per request. — 不必每个请求创建一个 JS 线程。
- CPU 密集的同步代码会阻塞该事件循环,让其他请求等待。
- 给函数加
async,不会自动把同步 CPU 运算搬到工作线程。 - 同步文件 API 等仍可能阻塞,不能认为 Node 所有 API 都是非阻塞的。
参考:Node.js — Don’t Block the Event Loop。
Node.js vs. Browser(与浏览器环境的区别)
The JavaScript language may be the same, but host APIs differ.
语言相同,不代表宿主环境提供的 API 相同。(p.11)
- Node.js 与 Chrome 都使用 V8。
- Not every browser uses V8. — 不能推断 Firefox、Safari 也用 V8。
- 标准 Node 环境没有网页的
document、DOM tree、布局与绘制系统。 - Node 可访问 OS-level primitives。
- Node 支持 CommonJS 和 ES Modules。
- 浏览器的原生模块机制是 ES Modules;
require()不是浏览器通用原生导入语法。 - 【补充】Having
fetchdoes not imply having a DOM. — 当前 Node 提供一些 Web APIs,包括 fetch,但不因此成为浏览器。
Evolving Runtime Capabilities(运行时能力演进)
课件列出的演进方向:(p.8)
- TypeScript support — TypeScript 支持。
- Built-in testing — 内建测试能力。
- Fine-grained security — 更细粒度权限。
- Promise-based core APIs — 核心库提供 Promise 风格接口。
【课件限定】These are version-dependent capabilities, not timeless absence/presence rules.
- 不要背“Node 永远不支持 TypeScript / 测试 / 权限控制”。
- 不要背“所有旧版本都支持这些能力”。
- 【补充】Native TypeScript execution does not necessarily perform type checking. — 原生去除类型语法不等于完整运行
tsc类型检查,也不是支持所有 TS 语法和配置。
Runtime Alternatives vs. Package Manager Alternatives(替代方案的层级)
课件提到 Deno、Bun,以及后面的 Yarn。(p.9–10、19)
- Deno and Bun are runtime alternatives.
- Yarn is a package-manager alternative.
- 不能把 Yarn 当成替代 V8 / Node 的运行时。
Deno 相关课件要点:
- 使用 V8。
- 提供细粒度 allow / deny 权限控制。
- 支持 TypeScript。
- 提供 fetch 等 Web APIs。
- 有标准库支持。
- 课件写“frequently faster”,不能变成“所有场景都比 Node 快”。
【课件限定】“Full web API” does not mean a full browser DOM.
- 支持一批 Web 标准 API,不等于运行一个完整浏览器。
- p.9 的要点主要描述 Deno,不能直接全部套到旁边出现的 Bun。
- p.10 给 logo 画叉,没有文字说明其含义,不能据此断言相应项目已经停止或无法使用。
参考:Deno — Security and Permissions。
Native HTTP Server(原生 HTTP 服务)
课件代码:(p.12)
javascript
import http from 'http';
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!\n');
});
server.listen(8080);
console.log('Server running on port 8080');Behavior(执行行为):
createServer()创建服务器对象,不立即监听端口。- 请求到达后才调用
(req, res)handler。 - 示例没有检查路径或 method,进入此普通请求 handler 的请求都执行同一响应逻辑。
writeHead()设置状态和响应头。end()写入可选最终数据并结束该次响应,不是停止整个服务器。listen()启动监听,监听建立是异步过程。- 【课件限定】The immediate console log does not prove listening has succeeded. — 紧随 listen 的同步日志可能先于监听成功;应在 listening callback 中输出确认信息。
- 未指定 host,不代表只监听 localhost。
TCP Echo Server(TCP 回显服务)
课件代码:(p.13)
javascript
import net from 'net';
const server = net.createServer(socket => {
socket.on('data', data => {
socket.write(data);
});
});
server.listen(1337, '127.0.0.1');This is a TCP echo server, not an HTTP application server.
- 每个新连接触发 connection listener,得到 socket。
- 收到一段数据后,原样写回该 socket。
- 默认情况下 data 是 Buffer。
127.0.0.1是 loopback,只接受本机通过该地址建立的连接。- 代码没有主动
socket.end(),写回不等于关闭连接。 - TCP is a byte stream, not a message protocol. — 一次发送不保证对应一次 data 事件。
- 浏览器访问它不意味着能得到合法 HTTP 页面;它没有生成 HTTP 状态行和响应头。
参考:Node.js — Net。
CommonJS Modules(CommonJS 模块)
CommonJS imports use require() and exports use module.exports.(p.15)
javascript
const http = require('http');
module.exports = {
myFunc() {},
myConst: 100,
};module.exports可以是函数、对象等值。require()返回被加载模块导出的值。- 仅设置 module.exports 不会自动发布到 npm。
- 【补充】Modules have their own scope. — 模块中的顶层变量不是自动成为所有模块共享的全局变量。
- 【补充】CommonJS modules are normally cached after loading. — 同一解析文件再次 require 通常复用缓存,不每次重执行全部顶层代码。
【课件修正】Resolution depends on the specifier, not “node_modules first, local files as fallback.”
| 写法 | 主要含义 |
|---|---|
require('http') | Node 内建模块 |
require('express') | bare package name,按包解析规则寻找 |
require('./routes') | 相对当前模块文件的本地路径 |
require('../models/task') | 相对路径 |
require('/absolute/path/file.cjs') | 绝对路径 |
- 包查找可能向父目录的 node_modules 继续寻找。
- 缺少
./的名称,不应假设自动寻找当前目录同名 JS 文件。
Export reassignment trap(导出覆盖):
javascript
module.exports = function first() {};
module.exports = { myConst: 100 };
// 最终 require 得到第二次赋值的对象,不会自动合并。【补充】exports alias trap:
javascript
exports.myConst = 100; // 通常有效:修改初始导出对象。
exports = { myConst: 100 }; // 只改局部别名,不等于替换 module.exports。参考:Node.js — CommonJS Modules。
ES Modules(原生 ES 模块)
Node.js supports both CommonJS and ECMAScript modules.(p.11、16)
javascript
import http from 'http';
const func1 = () => {};
const myConst = 81;
export { func1, myConst };- 这是 named exports,不是 default export。
- 对应导入:
import { func1, myConst } from './module.js'。 - p.15 的
myConst为 100,p.16 为 81,属于不同示例。 - 不能认为 import/export 必须由 Babel 转成 require 后 Node 才能执行。
【补充】Use explicit module mode for predictable examples.
.mjs:ES Module。.cjs:CommonJS。.js:受 package.json 的"type"等规则影响。"type": "module":明确该包下.js使用 ESM。- ESM 中没有自动可用的 CommonJS
require、module.exports、__dirname绑定。 - 不把 CJS / ESM 的写法任意混在同一文件中。
package.json(项目元数据与依赖配置)
package.json describes a package or application using JSON.(p.17)
- 包含依赖、脚本、仓库、开发依赖等信息。
- 是 JSON,不是 JS 对象字面量:不要写普通注释、单引号或尾逗号。
- 声明依赖不等于相应包已经安装。
main是包入口信息,不等于“执行 npm install 后自动启动服务器”。scripts定义可以运行的命令。dependencies与devDependencies用途不同,不等于前端依赖与后端依赖。
截图中有考试价值的字段:
| 字段 | 作用 |
|---|---|
name | 包名称 |
version | 包版本 |
description | 描述 |
main | 包的主要入口 |
scripts | 可运行脚本 |
scripts.test | test 脚本 |
author | 作者元数据 |
license | 许可证标识 |
dependencies | 应用 / 包运行所需依赖 |
devDependencies | 开发、构建、测试等依赖 |
repository.type | 仓库类型,例如 git |
repository.url | 源码仓库地址 |
keywords | 包搜索关键词 |
bugs.url | 问题反馈地址 |
homepage | 项目主页 |
截图里的默认 test 脚本输出 “no test specified” 并 exit 1,不是测试通过。
npm vs. Yarn(包管理器)
npm manages packages and runs package scripts; it does not replace the Node.js runtime.(p.18–20)
npm init:初始化 package.json。npm install:安装依赖。npm update:按允许范围更新依赖。- 【补充】npm update does not necessarily upgrade every package to its latest major version.
- Yarn 是替代包管理器,命令类似,但不是所有命令都与 npm 完全一致。(p.19)
- 课件强调 Yarn 的性能、一致性、规模与可配置性;不是无条件性能保证。
- p.20 的“copy from slide #7”与实际服务器代码页不一致;HTTP 示例在本 PDF p.12。
参考:npm — update。
2. Comparisons & Distinctions(易混淆概念对比)
| 概念 | 职责 | 不要混淆成 |
|---|---|---|
| V8 | JS 执行引擎 | npm、Express |
| libuv | 事件循环与异步 I/O 基础设施 | JS 语法转译器 |
| Node.js | 浏览器外 JS 运行时 | 完整浏览器 |
| Express | Node Web 框架 | Node 内建 HTTP 模块 |
| npm / Yarn | 包管理、脚本执行 | JS 执行引擎 |
| Deno / Bun | JS / TS 运行时 | npm 的别名 |
| Babel | 源码转换 | HTTP 服务器 |
| 对比 | http.createServer() | net.createServer() |
|---|---|---|
| 层级 | HTTP | TCP / IPC |
| 示例回调参数 | req, res | socket |
| 课件行为 | 返回 Hello World HTTP 响应 | 原样回显收到的数据 |
| 响应 API | writeHead、end | socket.write |
| 是否自动具有 HTTP 语义 | 是 | 否 |
| 对比 | CommonJS | ES Modules |
|---|---|---|
| 导入 | require(...) | import ... |
| 导出 | module.exports | export |
| 明确扩展名 | .cjs | .mjs |
| 顶层 this / 绑定 | 采用 CJS 包装环境 | ESM 语义,不提供 CJS 绑定 |
| 是否 Node 支持 | 是 | 是 |
3. APIs & Configurations(API 与配置速查)
HTTP / TCP(p.12–13)
import http from 'http'— 导入内建 HTTP 模块,不需 npm 安装;使用 ESM 环境。http.createServer((req, res) => {...})— 创建并返回 HTTP Server;注册请求回调,不立即监听。res.writeHead(200, { 'Content-Type': 'text/plain' })— 写状态和响应头,不等于结束响应。res.end('Hello, World!\n')— 提交最终正文并结束当前响应;不停止 server。server.listen(8080)— 请求监听端口,返回 server,不返回等待监听完成的 Promise。server.listen(8080, () => console.log('ready'))— 【补充】监听建立后运行回调。import net from 'net'— 导入内建 TCP / IPC 模块。net.createServer(socket => {...})— 创建并返回 net.Server;每个新连接获得 socket。socket.on('data', data => {...})— 注册异步数据到达事件,默认收到 Buffer。socket.write(data)— 写入 socket,返回布尔值反映缓冲 / 背压情况,不是 Promise,也不结束连接。server.listen(1337, '127.0.0.1')— 在本机 loopback 的指定端口监听。console.log(message)— 输出日志,不代表异步监听或响应已经完成。
Modules(p.15–16)
require('http')— 加载内建模块并返回导出值。require('express')— 加载外部包;先要有可解析的安装结果。require('./routes.cjs')— 加载本地模块,相对当前模块文件解析。module.exports = function () {...}— 将整个模块导出值设为函数。module.exports = { myFunc() {}, myConst: 100 }— 导出对象;后续整体赋值会覆盖它。export { func1, myConst }— 定义 named exports。import { func1, myConst } from './helpers.js'— 导入对应 named exports。"type": "module"— 【补充】明确.js文件使用 ESM。
npm / Project Commands(p.17–20)
npm init— 交互式创建 / 初始化 package.json,不启动服务。npm init -y— 【补充】采用默认答案初始化。npm install— 安装项目依赖,通常结合 package.json / lockfile。npm install express— 【补充】安装 Express,通常记录到 dependencies。npm install -D some-tool— 【补充】记录到 devDependencies。npm update— 更新到满足版本约束的版本,不保证跨 major。npm run start— 【补充】执行 scripts.start。node server.cjs— 【补充】用 Node 执行服务器入口。"scripts": { "start": "node server.cjs" }— 为启动命令命名;不是配置 HTTP 路由。"main": "index.js"— 包入口元数据,不自动等于启动脚本。
4. True / False Traps(判断题陷阱)
- True —
Node.js uses V8 and provides system-level APIs.— JS 引擎之外还有宿主能力。(p.3–7) - False —
Node.js is a web framework.— 它是运行时,Express 是框架。 - False —
Every browser uses the same V8 engine as Node.js.— p.11 对比的是 Chrome。 - False —
Node.js has the browser document DOM by default.— 不提供网页 DOM。(p.11) - False —
The entire Node.js process always has exactly one thread.— 单事件循环 JS 执行模型不等于整个进程单线程。(p.11;限定) - False —
An async function automatically moves CPU-heavy code off the event loop.— async 不自动创建工作线程。(补充) - True —
Blocking the event loop can delay other requests.— 同一事件循环会受影响。(补充) - False —
Node.js can only create HTTP servers.— p.13 是 TCP server。 - False —
http.createServer starts listening immediately.— 需 listen。(p.12) - False —
res.end stops the whole HTTP server.— 只结束当前响应。(p.12) - False —
A log immediately after listen proves the port was successfully bound.— listen 是异步建立。(p.12;限定) - True —
The net example echoes received data back to the client.— TCP 回显。(p.13) - False —
Each TCP write is guaranteed to produce one data event.— TCP 是字节流。(补充) - False —
Binding to 127.0.0.1 exposes the server on every network interface.— loopback 监听。(p.13) - False —
http and net must be installed from npm.— 内建模块。(p.14) - False —
Node.js supports CommonJS but not ES Modules.— 两者均支持。(p.11、15–16) - False —
require('foo') automatically falls back to ./foo.js.— specifier 决定解析方式。(p.15;修正) - False —
Repeated module.exports assignments are automatically merged.— 后一次整体赋值覆盖前一次。(p.15) - False —
Setting module.exports automatically publishes the package.— 导出与发布是不同动作。(p.15) - False —
package.json is executable JavaScript and may contain ordinary comments.— 是 JSON。(p.17) - False —
The main field automatically starts an application.— main 不是启动命令。(p.17) - False —
npm init starts an HTTP server.— 初始化元数据。(p.20) - False —
npm update always installs the latest major version of every dependency.— 通常受版本范围限制。(p.18;补充) - False —
Yarn is an alternative JavaScript runtime.— 是包管理器。(p.19) - False —
Native TypeScript execution necessarily includes type checking.— 类型语法处理与类型检查不同。(p.8;补充) - False —
Deno is always faster than Node.js.— 课件也未作 always 保证。(p.9)
5. Exam Quick Reference(考前速查)
- Node = V8 + libuv + system APIs。(p.3–7)
- Single-threaded JS ≠ one-thread process;同步重活阻塞事件循环。
- No browser DOM;有 fetch 不代表有 document。(p.11)
- HTTP: createServer → request handler → writeHead → end;listen 开端口。(p.12)
- TCP: net.createServer → socket data → socket.write;默认 Buffer;非 HTTP。(p.13)
- 127.0.0.1: 本机 loopback。
- Built-ins: http / net / fs / path / events / buffer 等,不需 npm 安装。(p.14)
- CJS: require / module.exports;重复整体赋值覆盖。(p.15)
- Resolution:
'express'包;'./x'文件;不是无条件本地 fallback。 - ESM: import / export;
.mjs或明确"type": "module"。(p.16) - package.json: metadata / dependencies / devDependencies / scripts。(p.17)
- npm: init 初始化;install 安装;update 按范围更新;node 执行入口。
- Yarn: 包管理器;Deno/Bun: 运行时。
Lecture 19 — Node.js and Express.js
本章共 18 页。p.14 与 p.17 的 Router 示例重复。
MongoDB / Mongoose 微型服务位于本章 API 部分,标为 【编程题扩展】;数据库语法不是这三份 PPT 已讲解的内容。
1. Core Concepts(核心概念)
Native Request / Response(原生请求与响应)
The HTTP request is an IncomingMessage; the response is a ServerResponse.(p.3–5)
req:客户端传来的请求信息。res:服务器正在构造的响应。- Node 的原生 HTTP API 层级较低,不自动把 JSON 请求体变成业务对象。
- 【补充】The request body is streamed. — body 可能分多个 chunk 到达,不保证请求回调开始时已经完整解析。
Native request fields(p.4):
req.headers— 请求头对象。req.method— HTTP method。req.url— 通常包含请求路径与 query 的请求目标字符串,不保证是带协议和主机的完整绝对 URL。url.parse(req.url, true)— 课件旧式解析,第二个参数 true 表示将 query 解析为对象。
【课件补全 / 限定】
- 使用
url.parse()前需导入url,片段没有展示。 'Headers: ' + req.headers通常只得到[object Object],不是完整打印所有字段。url.parse(...)返回对象,直接字符串拼接也不等于结构化展示。- 可改
console.log('Headers:', req.headers)。 url.parse()属于 legacy 风格;新代码常用 WHATWG URL,但考试需认得课件写法。
参考:Node.js — URL。
JSON Text vs. JSON Content Type(正文和类型是两回事)
p.5:
javascript
const body = JSON.stringify({
username: 'heminggs',
email: 'graham.hemingway@vanderbilt.edu',
});随后设置 Content-Type: text/plain。
Serializing an object as JSON does not automatically set an HTTP header.
- 正文是 JSON 格式文本。
- 课件明确把响应媒体类型写成 text/plain。
- 不能答“JSON.stringify 会自动设置 application/json”。
- 常规 JSON API 更适合
application/json,Express 可用res.json()。
【课件修正】Content-Length is measured in bytes, not JavaScript string length.
body.length是字符串的 UTF-16 code units 数量。- 对课件里的 ASCII 文本恰好通常与 UTF-8 字节数一致。
- 对中文、emoji 不可靠。
- 应使用
Buffer.byteLength(body, 'utf8'),或交给 Express 处理。
参考:Node.js — HTTP、Node.js — Buffer。
Express Application(Express 应用)
Express adds routing and middleware conveniences on top of Node’s HTTP APIs.(p.6、15–16)
javascript
const express = require('express');
const app = express();三件事必须分开:
| 写法 | 干什么 |
|---|---|
express() | 创建应用对象 |
app.use(...) | 注册中间件 / 挂载 Router |
app.get(path, handler) | 注册 GET 路由 |
app.post(path, handler) | 注册 POST 路由 |
app.listen(port, callback) | 启动 HTTP 端口监听 |
app.use()本身不启动服务器。- 注册 route 不等于调用客户端请求。
- 应用可先把 pipeline 配置好,最后监听。
app.listen()返回底层 HTTP Server。- 【补充】Express app 可作为
http.createServer(app)的请求处理函数。
Middleware Pipeline(中间件管线)
Middleware order affects request handling.(p.7–13)
课件顺序:
- Static handler。
- Logger。
- JSON body parser。
- URL-encoded body parser。
- Route handler。
中间件可以:
- 读取 / 修改 req、res。
- 完成响应。
- 调用
next()把控制权交给后面的匹配 handler。 - 传递错误。
A handler must eventually respond or pass control onward.
不响应,也不 next,请求可能一直挂起。
不是所有请求都会走完全部步骤:
- 静态文件找到并响应,后面的 logger / parser / route 可能不再执行。
- 静态文件未找到,默认通常继续 next。
- 解析器只处理符合媒体类型等条件的 body。
- 出错后可进入错误处理管线。
课件顺序的直接考点:
- Static before logger can bypass logging for served static files.
- 若希望覆盖静态资源请求,把 logger 放 static 前。
- body parser 应放在读取 req.body 的 route 前。
- 权限检查放在已经发完响应的 route 后面,无法保护它。
参考:Express — Using Middleware。
next() vs. return vs. Response Completion
next() passes control; return exits the current JavaScript function.
javascript
app.use((req, res, next) => {
console.log('A');
next();
console.log('B');
});后面的同步 handler 可以在 B 之前执行。
next()不表示当前函数后面的代码永远不运行。res.send()/res.json()完成响应,但不自动退出当前 JS 函数。- 常写
return res.status(400).json(...)防止继续执行后续业务逻辑。 - 已完成响应后再
next(),可能让后面再次响应,产生 headers already sent 等问题。 next(err):转交错误处理,不是普通继续。- 【补充】错误处理中间件用四个参数
(err, req, res, next)。 - 404 通常表示没有 handler 处理,不会自动生成一个 Error 并进入你的错误 handler。
Body Parsing(请求体解析)
Body parsers populate req.body; they do not parse all input formats.(p.7–13)
课件:
javascript
app.use(bodyParser.json({}));
app.use(bodyParser.urlencoded({ extended: true }));必要区分:
json():JSON body。urlencoded():application/x-www-form-urlencodedbody。extended: true:允许较丰富的对象 / 数组编码,例如嵌套字段。- extended does not mean “also parse JSON.”
- 它不是解析 query string 的开关。
- 两者不负责 multipart 文件上传。
- 解析成功不代表数据可信或符合业务要求。
req.body是客户端输入,需要检查类型和值。- 【补充】现代 Express 提供
express.json()、express.urlencoded(),不必为普通用法单独安装 body-parser。 - 未匹配 body / 未配置 parser 时,req.body 的具体默认形态受版本影响;不要假定永远是已填好的对象。
参考:Express — Built-in Middleware。
Static Files, Logger & Settings(静态文件、日志与配置)
课件配置:(p.7)
app.set('view engine', 'pug')— 默认模板引擎。app.set('views', pugPath)— 模板目录。path.join(__dirname, '../../public')— 静态文件所在目录。express.static(staticPath)— 静态文件中间件。logger('dev')— 日志中间件工厂调用。
【课件补全】:
path需要导入 Node path 模块。__dirname为 CommonJS 中当前模块目录,不是浏览器变量。logger没有展示导入;常见实现为 Morgan,但名字本身不是 Express 内建 API。app.set()设置配置,不是加入一个“每次请求都执行的路由步骤”。- static 文件目录与 views 模板目录职责不同。
- 挂载
app.use('/assets', express.static(publicDir))后,URL 前缀/assets不要求磁盘上也有 assets 文件夹。
Routes & Router(路由与模块化)
An Express route combines an HTTP method, a path pattern, and handlers.(p.14、17–18)
- 相同 path 可以有不同 method。
app.get('/foo', ...)不等于处理所有 method。- 【补充】Express 的 GET 路由在没有更具体 HEAD 处理时也可能处理 HEAD。
- route path 匹配不把 query string 当作路径模式的一部分。
express.Router()创建可挂载的路由模块,不单独监听端口。app.use('/api', router)为其路径增加挂载前缀。router.get('/tasks', ...)挂载后实际匹配/api/tasks。- 可在独立模块导出 router,主应用 require / import 后挂载。
app.use vs. app.METHOD:
app.use('/api', middleware):按挂载前缀匹配,不限定单一 HTTP method。app.get('/api', handler):GET 路由匹配,不等于前缀下所有子路径。- 不把
app.use()简单记成“开一个 GET 接口”。
Regex Route Example(正则路由)
课件:(p.14、17)
javascript
router.post(
/^\/commits\/(\w+)(?:\.\.(\w+))?$/,
(req, res) => {
const from = req.params[0];
const to = req.params[1] || 'HEAD';
res.send('commit range ' + from + '..' + to);
}
);考试拆解:
post:请求 method 为 POST。^/$:整个路径从头到尾匹配。\/commits\/:固定/commits/。(\w+):第一个捕获组,至少一个 word character。(?:...):非捕获分组,不占 req.params 的数字捕获位置。\.\.:两个字面点。(\w+):第二个捕获组。?:整个..to部分可选。req.params[0]/[1]:捕获结果,字符串。'HEAD'是缺省终点字符串,不是此处请求 method 改为 HEAD。\w常见范围为字母、数字、下划线,不包括-。
| 请求 | 行为 |
|---|---|
POST /commits/main | commit range main..HEAD |
POST /commits/main..dev | commit range main..dev |
POST /commits/123 | commit range 123..HEAD |
POST /commits/main-dev | 不匹配 \w+ |
POST /commits/main.. | 不匹配,第二组不能空 |
GET /commits/main | 不匹配此 POST route |
POST /commits/main/extra | 不匹配末尾锚定 |
Request Data Sources(请求数据来源)
Path parameters, query parameters, body data, and cookies are different sources.(p.15)
例如:
text
POST /api/tasks/abc?notify=true
Content-Type: application/json
{"title":"Review"}- path parameter:
req.params.id === 'abc',前提是 route 为/tasks/:id。 - query:
req.query.notify。 - body:
req.body.title,前提是正确解析。 - cookies:
req.cookies,通常需要 cookie-parser。 - 不能认为
req.params包含所有用户输入。 - 不要直接把整个 req.body / req.query 当数据库 filter 或更新对象。
Cookie APIs(Cookie 读写)
【课件修正】res.cookie() sets cookies; it does not read client cookies.(p.16)
- 读取:
req.cookies/req.signedCookies。 - 设置:
res.cookie(...),构造 Set-Cookie 响应头。 - 删除:
res.clearCookie(...),要求客户端使对应 Cookie 过期。 - 设置 Cookie 不等于完成整个 HTTP 响应。
- 通常需要后续请求才能在 req.cookies 看到客户端回传的新 Cookie。
- Signed means integrity protection, not encryption. — 签名用于检测篡改,不代表值保密。
- 解析 Cookie 的中间件与 express.json 是不同能力。
Response Construction(响应构造)
Setting response metadata is different from sending a response.(p.16)
| 只配置 / 不单独完成响应 | 通常会发送 / 完成响应 |
|---|---|
status、set、append、type | send、json、jsonp |
cookie、clearCookie | end、sendStatus |
location、attachment | redirect、sendFile、download |
links、vary | render 无 callback 时通常发送 |
res.status(404)只设置状态,不发送 404 页面。res.sendStatus(404)设置状态并发送相应状态文本。res.location('/x')只设 Location,不等于 redirect。res.attachment('a.csv')只设下载相关 header,不自动产生文件正文。res.get()读响应头,不是客户端请求头。res.format()根据 Accept 做内容协商,不是 JSON 格式化。res.jsonp()是 JSONP,不是 json 的拼写变体。res.sendFile()发送现有文件;res.render()经模板引擎生成内容。- 使用 render callback 时,通常由调用方决定如何发送结果。
- HTTP 204 等无正文状态有特殊语义,不能假设所有 sendStatus 都有正文。
Express 4 vs. 5 Error Handling(必要版本限定)
【补充】Async error behavior differs by Express version.
- Express 5 对 route / middleware 返回 Promise 的 rejection 可自动转交错误处理。
- Express 4 的 async handler 常需
try/catch + next(err)或 wrapper。 - 不把“Express 自动捕获所有异步错误”当作跨版本事实。
- 独立 timer callback 等异步上下文也不能无条件假定被框架捕获。
2. Comparisons & Distinctions(易混淆概念对比)
Native Node vs. Express
| 功能 | 原生 Node HTTP | Express |
|---|---|---|
| 创建服务逻辑 | http.createServer(handler) | express() |
| 开始监听 | server.listen(...) | app.listen(...) 或底层 server.listen |
| 方法判断 | 读 req.method 自行判断 | app.get / post 等 |
| 路径处理 | 读 req.url,自行解析 | route pattern / req.params / req.path |
| 请求体 | stream,自行处理 | 注册 parser 后读 req.body |
| JSON 响应 | stringify + headers + end | res.json(obj) |
| 模板 | 自行连接引擎 | view settings + res.render |
| 模块化路由 | 自行组织 | express.Router |
Request Fields
| 字段 | 示例含义 | 易错点 |
|---|---|---|
req.params | /tasks/:id 的 id | 不含所有 query / body |
req.query | ?page=2 | 值不保证已经是 number |
req.body | POST JSON / 表单 body | 依赖 parser,类型不可信 |
req.cookies | 客户端 Cookie | 依赖解析中间件 |
req.path | 当前路径,不含 query | Router 内通常不含挂载前缀 |
req.baseUrl | Router 的挂载路径 | 不是带协议主机的完整 URL |
req.originalUrl | 原始 URL,含 query | 不等于纯 pathname |
Input Formats
| 格式 | 常用解析方式 | 不负责什么 |
|---|---|---|
| JSON body | express.json() | 不解析 multipart |
| URL-encoded form body | express.urlencoded() | 不是 query parser 开关 |
| Query string | req.query / query parser | 不解析 JSON body |
| Cookies | cookie-parser 等 | 不是 sessionStorage |
| File upload | multipart middleware | 普通 json/urlencoded 不够 |
Common Response Choices
| 目的 | API |
|---|---|
| 返回对象 / 数组 JSON | res.json(data) |
| 返回字符串 / HTML | res.send(text) |
| 只改状态,稍后发数据 | res.status(code) |
| 状态码 + 默认状态文本 | res.sendStatus(code) |
| 跳转 | res.redirect(url) |
| 只设 Location | res.location(url) |
| 发送文件 | res.sendFile(path) |
| 提示附件下载并发送文件 | res.download(path) |
| 模板生成 HTML | res.render(view, locals) |
| 无正文结束 | res.end() |
3. APIs & Configurations(API 与配置速查)
3.1 Express 高频“思维导引”
const app = express()— 先建应用,还没开端口。app.use(middleware)— 给后续请求挂公共处理步骤;无 path 默认从/挂载。app.use('/api', middleware)— 只对该挂载路径范围执行公共步骤;不是启动服务。app.use('/api', router)— 把一组接口挂到 /api 前缀。app.get('/tasks', handler)— 注册 GET 接口。app.post('/tasks', handler)— 注册 POST 接口。app.patch('/tasks/:id', handler)— 【补充】注册局部更新接口。app.put('/tasks/:id', handler)— 【补充】注册 PUT 接口;替换还是更新需业务实现遵守语义。app.delete('/tasks/:id', handler)— 【补充】注册删除接口,不会自动删数据库。app.all('/x', handler)— 【补充】对该 route 匹配多种 HTTP method。app.listen(8080, callback)— 最后开 HTTP 端口监听,返回 HTTP Server。http.createServer(app)— 显式创建底层 HTTP server;随后用 server.listen。app.set('name', value)— 设置应用选项,不是创建接口。app.get('view engine')— 单参数时可读配置;与app.get('/x', handler)的注册路由重载区分。next()— 这一层处理完,继续后面的匹配层。next(err)— 交给后面的错误处理中间件。return res.json(data)— 发响应并退出当前 JS handler。express.Router()— 建一组可独立组织的路由,不会自己监听。
3.2 Pipeline Configuration(p.7–13)
app.set('view engine', 'pug')— 指定默认模板引擎。app.set('views', pugPath)— 指定模板查找目录。path.join(__dirname, './')— 以当前模块目录构造路径;不读文件。path.join(__dirname, '../../public')— 构造静态资源目录路径。express.static(staticPath)— 返回静态文件 middleware;本行工厂调用不等于立即发送文件。app.use(express.static(staticPath))— 注册静态资源处理;找到文件可能直接响应。logger('dev')— 创建 dev 格式 logger middleware;需正确导入对应库。bodyParser.json({})— 课件 JSON body 解析器工厂。bodyParser.urlencoded({ extended: true })— 课件 URL-encoded body 解析器,支持丰富嵌套编码。app.use(express.json({ limit: '100kb' }))— 【补充】内建 JSON parser,并限制 body 大小。app.use(express.urlencoded({ extended: true }))— 【补充】内建表单 body parser。app.use(cookieParser(secret))— 【补充】解析 Cookie,可验证签名;需安装、导入 cookie-parser。
3.3 Request Properties(p.15 全部字段)
以下均为读取当前请求信息的属性,不是“发送响应”的方法。由客户端或代理提供的值需按上下文验证。
req.app— 处理此请求的 Express application 引用。req.baseUrl— 当前 Router / middleware 的匹配挂载路径。req.body— 已解析的请求体,依赖前面的 parser。req.cookies— 已解析的普通 Cookie,通常由 cookie-parser 提供。req.fresh— 根据条件请求与响应校验信息判断客户端缓存是否仍 fresh,不是“数据库数据最新”。req.hostname— 请求主机名,不含端口;代理信任设置会影响来源。req.ip— Express 判断的客户端 IP,受 trust proxy 影响。req.ips— 可信代理配置下的转发 IP 链;未信任代理时通常为空数组。req.method— HTTP method,例如'GET'、'POST'。req.originalUrl— 原始请求 URL,保留挂载前缀与 query。req.params— 路由路径参数;正则捕获可使用数字索引。req.path— URL 路径部分,不含 query;挂载上下文会影响结果。req.protocol—'http'/'https',可受可信代理头影响。req.query— query 解析结果;不要假定所有值都是简单字符串或数字。req.route— 当前匹配 route 的描述信息。req.secure— 通常相当于req.protocol === 'https'。req.signedCookies— 通过签名校验的 Cookie 值;不是解密后的秘密数据。req.stale— 与 req.fresh 相反的缓存新鲜度判断。req.subdomains— 根据 hostname 与 subdomain offset 设置提取子域。req.xhr— 根据X-Requested-With: XMLHttpRequest判断;fetch 不保证自动带该头,也不能用作可信安全判断。
常用补充:
req.get('Content-Type')— 读取请求头,字段名大小写不敏感。req.headers— Node 请求头对象,常用键名小写。req.url— 当前处理上下文中的 URL,挂载 Router 时可能临时去掉前缀。
3.4 Response Methods(p.16 全部方法)
设置 / 读取元数据,不单独结束响应:
res.status(201)— 设置状态码并返回 res,常用于链式调用。res.set('X-App', 'cs4288')— 设置响应头,通常覆盖该字段已有设置,返回 res。res.append('Set-Cookie', value)— 追加响应头值,返回 res;之后 set 同字段仍可覆盖。res.get('Content-Type')— 返回已设置的响应头值,未设置通常为 undefined。res.type('json')— 设置对应 Content-Type,返回 res,不发送正文。res.location('/tasks/1')— 设置 Location,返回 res,不单独跳转。res.attachment('report.csv')— 设置附件下载相关 header,不读取或发送文件内容。res.cookie('theme', 'dark', { httpOnly: true })— 设置 Set-Cookie,返回 res,不读取请求 Cookie。res.clearCookie('theme', { path: '/' })— 设置清除 Cookie 的响应头;范围选项需匹配。res.links({ next: '/tasks?page=2' })— 设置 Link 响应头。res.vary('Accept')— 将字段加入 Vary,告诉缓存响应可能依该请求头变化。
发送 / 结束响应:
res.send('Hello World!')— 发送正文并完成响应;字符串通常按 HTML 类型处理,返回 res。res.json({ ok: true })— 序列化为 JSON、设置相应类型并完成响应,返回 res。res.jsonp({ ok: true })— 发送 JSONP;可根据配置的 query callback 包装 JS 调用,不是普通 JSON。res.sendStatus(404)— 设置状态并发送默认状态文本,返回 res;无正文状态遵循 HTTP 规则。res.end()— 结束响应,可不带 body;继承 Node 的低层响应语义。res.redirect('/login')— 默认通常为 302 跳转,设置状态 / Location 并完成响应。res.redirect(303, '/tasks')— 明确指定跳转状态。res.sendFile(absolutePath)— 异步传输文件;通常需绝对路径,或提供 root 选项。res.download(filePath, 'report.csv')— 发送文件并设置附件下载文件名;异步传输。res.render('landing', { title: 'Hey' })— 渲染模板;未提供 callback 时通常发送生成结果。res.render('landing', data, (err, html) => {...})— callback 获得错误或 HTML;此用法不会自动替你发送 html。res.format({ json() {...}, html() {...} })— 根据客户端 Accept 选择分支,由分支完成响应;无匹配且无 default 可产生 406。
补充:
res.headersSent— 判断响应头是否已发出,错误处理中用于避免再次设置状态 / 头。res.locals.user = user— 为当前请求保存模板变量;不是跨所有请求的全局状态。
3.5 Router & Native HTTP(p.3–5、14、17–18)
const router = express.Router()— 创建 Router 实例。router.get('/tasks/:id', handler)— 在 Router 内注册 GET route,id 进入 req.params。router.post('/tasks', handler)— 注册 POST route。app.use('/api', router)— 将 Router 挂载到 /api。module.exports = router— CommonJS 导出 Router,供主应用挂载。url.parse(req.url, true)— 旧式 URL 解析,true 使 query 解析成对象。JSON.stringify(obj)— 同步生成 JSON 字符串,不设置响应头。Buffer.byteLength(body, 'utf8')— 同步计算 UTF-8 字节数,适合 Content-Length。res.writeHead(200, headers)— 原生 Node 写状态和响应头。res.end(body)— 原生 Node 发送最终正文并结束。
3.6 【编程题扩展】完整微型服务:HTTP + Express + Middleware + Mongoose
Possible exam prompt:
Create an HTTP service with middleware and two routes. Save a task to MongoDB and retrieve a task by its ID.
两个接口、两个路径模式:
| Method | URL | 行为 |
|---|---|---|
| POST | /api/tasks | 创建任务 |
| GET | /api/tasks/:id | 根据 MongoDB ObjectId 读取任务 |
写题顺序:
- require 依赖,
express()建 app。 - 公共日志 middleware。
- JSON parser。
- Schema → Model。
- Router 上写接口。
- app.use 挂载 Router。
- 404 → error handler。
- 先连接数据库,再开始监听 HTTP。
运行准备:
bash
npm init -y
npm install express mongoose
node server.cjs下面代码作为 server.cjs 使用。需要已有 MongoDB 服务,默认连接本机 27017。示例已做 Node 语法检查;未连接实际数据库做端到端运行。
javascript
const http = require('node:http');
const express = require('express');
const mongoose = require('mongoose');
const app = express();
// 1. 公共中间件:在 parser / routes 之前注册。
// finish 事件用于记录响应完成时的最终状态。
app.use((req, res, next) => {
const startedAt = Date.now();
res.on('finish', () => {
console.log(
req.method,
req.originalUrl,
res.statusCode,
`${Date.now() - startedAt}ms`
);
});
// 不发送响应,所以要让请求继续。
next();
});
// 2. JSON body parser。
// 只有经过这里后,匹配的 JSON body 才进入 req.body。
app.use(express.json({ limit: '100kb' }));
// 3. Schema:定义应用侧字段、默认值与校验。
const taskSchema = new mongoose.Schema(
{
title: {
type: String,
required: true,
trim: true,
maxlength: 100,
},
done: {
type: Boolean,
default: false,
},
},
{
timestamps: true, // 自动维护 createdAt / updatedAt。
}
);
// Model 是操作这一类文档的入口。
// 默认通常映射到 tasks collection。
const Task = mongoose.model('Task', taskSchema);
// 4. 兼容 Express 4 / 5 的 async 错误包装。
// 路由 Promise 失败时交给 next(err)。
// 这里从 Promise.then 调用 fn,也能把同步 throw 转成 rejection。
const asyncRoute = fn => (req, res, next) => {
Promise.resolve()
.then(() => fn(req, res, next))
.catch(next);
};
const router = express.Router();
// 5. POST /api/tasks:校验 → 写库 → 201 JSON。
router.post(
'/tasks',
asyncRoute(async (req, res) => {
const body = req.body;
// JSON 解析成功不等于数据满足业务要求。
// 不把整个 req.body 无筛选地传给数据库。
if (
!body ||
typeof body.title !== 'string' ||
!body.title.trim() ||
body.title.trim().length > 100 ||
(
body.done !== undefined &&
typeof body.done !== 'boolean'
)
) {
return res.status(400).json({
error: 'title 必须是 1–100 字符;done 必须是 boolean',
});
}
// create 会真正写入数据库,返回 Promise。
const task = await Task.create({
title: body.title.trim(),
done: body.done ?? false,
});
// location 只设置 header,不跳转。
// json 负责发送数据并结束响应。
return res
.status(201)
.location(`/api/tasks/${task.id}`)
.json(task);
})
);
// 6. GET /api/tasks/:id:参数校验 → 查库 → JSON。
router.get(
'/tasks/:id',
asyncRoute(async (req, res) => {
// 本例使用默认 ObjectId,按 24 位十六进制格式检查。
// 格式合法不代表数据库里一定存在。
if (!/^[0-9a-fA-F]{24}$/.test(req.params.id)) {
return res.status(400).json({
error: 'id 必须是 24 位十六进制 ObjectId',
});
}
// findById 返回 Mongoose Query。
// lean:只读展示使用普通对象,跳过 Document 包装。
// exec:执行查询并返回 Promise。
const task = await Task.findById(req.params.id)
.lean()
.exec();
if (!task) {
return res.status(404).json({
error: 'Task not found',
});
}
return res.json(task);
})
);
// 7. Router 内没有 /api;挂载时统一补上。
app.use('/api', router);
// 8. 没有任何前面的 route 完成响应时,返回 route 404。
// 这和“合法 id 但没有该任务”的 404 是不同情形。
app.use((req, res) => {
return res.status(404).json({
error: 'Route not found',
});
});
// 9. 错误中间件必须保留四个参数,放在需要处理的逻辑后面。
app.use((err, req, res, next) => {
if (res.headersSent) return next(err);
if (err.type === 'entity.parse.failed') {
return res.status(400).json({ error: 'Invalid JSON' });
}
if (err.type === 'entity.too.large') {
return res.status(413).json({ error: 'Body too large' });
}
if (
err.name === 'ValidationError' ||
err.name === 'CastError'
) {
return res.status(400).json({ error: err.message });
}
console.error(err);
return res.status(500).json({
error: 'Internal server error',
});
});
// 10. 启动:先 DB ready,再开放 HTTP。
async function main() {
const uri =
process.env.MONGO_URI ||
'mongodb://127.0.0.1:27017/cs4288';
const port = Number(process.env.PORT || 8080);
await mongoose.connect(uri, {
serverSelectionTimeoutMS: 5000,
});
// Express app 是 HTTP request listener。
const server = http.createServer(app);
// listen 本身不返回 Promise,所以这里包装一下以捕获启动失败。
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(port, '127.0.0.1', resolve);
});
console.log(`HTTP listening on http://127.0.0.1:${port}`);
}
main().catch(async err => {
console.error('Startup failed:', err);
await mongoose.disconnect();
process.exitCode = 1;
});发送请求:
bash
curl -i -X POST http://127.0.0.1:8080/api/tasks \
-H 'Content-Type: application/json' \
-d '{"title":"Review Express","done":false}'从响应中复制 _id,替换第二条命令末尾的 ID:
bash
curl -i http://127.0.0.1:8080/api/tasks/507f1f77bcf86cd799439011这题的关键行为:
app.use()是注册处理步骤。http.createServer(app)建 HTTP server。server.listen()开监听。await mongoose.connect()连接数据库,不创建 HTTP 端口。- Schema / Model 定义不等于已经插入数据。
Task.create()真正插入。findById()是 Query,执行后可能得到 null。- 异步数据库等待不会自动让这个请求的 handler 阻塞所有其他 JS 回调。
return防止发完错误响应后继续查库 / 再发一次响应。
3.7 【编程题扩展】MongoDB vs. Mongoose:先分层
| 名称 | 是什么 | 典型代码 |
|---|---|---|
| MongoDB | 数据库服务 | 监听 27017 等 |
mongodb | 官方 Node driver | MongoClient、collection |
| Mongoose | 基于 driver 的 ODM | Schema、Model、Document、Query |
| Schema | 应用侧结构与规则 | new mongoose.Schema(...) |
| Model | 一类文档的操作入口 | Task.find(...) |
| Document | 一条 Mongoose 文档实例 | task.save() |
| Query | 可构造、执行的查询对象 | .sort().limit().exec() |
Mongoose schema is not automatically a MongoDB server-side collection validator.
Mongoose 校验不会自动限制所有绕过 Mongoose 的数据库写入。
Mongoose 高频语法
await mongoose.connect(uri)— 异步建立默认连接;一般在启动时连接,别每个请求重新连接。new mongoose.Schema(definition, options)— 定义结构和规则,不插入数据。mongoose.model('Task', schema)— 创建 / 获取 Model;默认通常按复数集合名映射。new Task({ title: 'A' })— 创建内存中的 Document,尚未保存。await task.save()— 校验并保存 Document;新文档插入,已有文档保存修改。await Task.create({ title: 'A' })— 创建并保存,返回 Document。await Task.find({ done: false }).exec()— 返回匹配文档数组,未匹配为[]。await Task.findOne({ title: 'A' }).exec()— 返回一条文档或 null。await Task.findById(id).exec()— 根据_id查一条文档或 null;无效格式可能 CastError。await Task.find({}).sort({ createdAt: -1 }).limit(20).lean().exec()— 按时间倒序取最多 20 条普通对象。.select('title done')— 指定查询字段;_id通常仍包含。.lean()— 查询返回普通对象,不带通常 Document 的 save / 变更跟踪能力。.exec()— 执行 Query,返回 Promise。await Task.updateOne({ _id: id }, { $set: { done: true } }, { runValidators: true })— 更新并返回写入结果,不直接返回更新后的任务。await Task.findByIdAndUpdate(id, { $set: { done: true } }, { returnDocument: 'after', runValidators: true })— 返回更新后的文档或 null。await Task.deleteOne({ _id: id })— 返回删除结果,检查 deletedCount。await mongoose.disconnect()— 关闭 Mongoose 连接。
Mongoose traps:
- Query 可 await,但它不是可随意重复执行的普通 Promise。
- 默认 findOneAndUpdate 风格通常返回更新前文档;想要更新后需明确选项。
- update validators 通常需
runValidators: true,且不等同于完整 document save 校验。 unique: true表示唯一索引意图,不是普通 Mongoose validator;重复键是数据库错误。timestamps: true维护 createdAt / updatedAt,不等于自动 TTL 删除。.lean()不等于“数据库完全不执行查询”,它省略的是结果 Document 包装。
参考:Mongoose — Queries、Schemas、Validation、Lean、findOneAndUpdate。
同样的工作,用原生 MongoDB driver 怎么写
javascript
const { MongoClient, ObjectId } = require('mongodb');
async function main() {
// 启动时创建、连接并复用 client。
const client = new MongoClient(
'mongodb://127.0.0.1:27017'
);
await client.connect();
try {
const tasks = client
.db('cs4288')
.collection('tasks');
// 返回 InsertOneResult,不是完整 Mongoose Document。
const inserted = await tasks.insertOne({
title: 'Review Express',
done: false,
});
const id = inserted.insertedId;
// 返回普通文档对象或 null。
const task = await tasks.findOne({ _id: id });
// find 返回 cursor,不是直接返回数组。
const list = await tasks
.find({ done: false })
.sort({ _id: -1 })
.limit(20)
.toArray();
const updated = await tasks.updateOne(
{ _id: id },
{ $set: { done: true } }
);
console.log(
task,
list,
updated.matchedCount,
updated.modifiedCount
);
// 从 URL 字符串构造 ObjectId 前,先检查 / 捕获非法输入。
const exampleId = new ObjectId('507f1f77bcf86cd799439011');
console.log(exampleId);
} finally {
// 脚本结束才关;Web 服务不要每次请求后 close。
await client.close();
}
}
main().catch(console.error);client.db('cs4288')— 选择数据库句柄,不表示单独执行一次网络查询。db.collection('tasks')— 获取集合句柄,不代表已经插入或创建文档。collection.insertOne(doc)— 异步插入,返回结果里的 insertedId。collection.find(filter)— 返回 cursor。cursor.toArray()— 异步读取 cursor 结果为数组。collection.findOne(filter)— 异步返回一条文档或 null。collection.updateOne(filter, update)— 返回写入结果。collection.deleteOne(filter)— 返回删除结果,检查 deletedCount。new ObjectId(id)— 将合法字符串转换成 BSON ObjectId;字符串 ID 与 ObjectId 不是同一类型。
Driver vs. Mongoose 最容易混:
| 操作 | Native driver | Mongoose |
|---|---|---|
| 查多条的中间结果 | cursor | Query |
| 取数组 | .find(...).toArray() | await Model.find(...).exec() |
| 插入一条 | insertOne() → result | create() → Document |
| 普通查询结果 | 普通文档对象 | 通常 Document,lean 后普通对象 |
| 结构规则 | 数据库配置 / 应用代码 | Schema |
| 保存实例 | 没有 Mongoose doc.save 语义 | doc.save() |
参考:MongoDB Driver — Find、Insert。
4. True / False Traps(判断题陷阱)
HTTP / Pipeline
- True —
Node's HTTP request object is an IncomingMessage.— 原生请求类型。(p.4) - False —
Node automatically parses every JSON request into req.body.— 原生 Node 不自动提供该业务对象。(p.4;补充) - False —
JSON.stringify automatically sets Content-Type to application/json.— 序列化与响应头不同。(p.5) - False —
JavaScript string length always equals HTTP Content-Length.— 应计算字节数。(p.5;修正) - False —
express() starts listening on a port.— 创建 app 不等于 listen。(p.6) - False —
app.use() starts the HTTP server.— 注册 middleware。(p.7) - True —
Middleware registration order affects behavior.— 本章 pipeline 核心。(p.7–13) - False —
Every request executes every middleware in the application.— 提前响应、未匹配、错误都可能改变流程。(p.8–13) - False —
A logger after static middleware necessarily sees all static-file requests.— static 可提前完成。(p.7–9) - False —
Calling next automatically exits the current function.— next 与 return 不同。(补充) - False —
Calling res.send automatically prevents later JavaScript statements from running.— 结束响应不等于退出函数。(补充) - False —
Middleware that neither responds nor calls next is automatically skipped.— 可能挂起请求。(补充) - False —
A body parser placed after a responding route still prepares req.body for that route.— 顺序不对。(p.7–13) - False —
extended: true enables JSON parsing.— 是 URL-encoded 嵌套解析选项。(p.7) - False —
express.json parses multipart file uploads.— 不负责 multipart。(补充) - False —
Parsed body data is automatically safe and valid.— 仍需校验。(补充)
Router / Request
- False —
express.Router starts a separate HTTP listener.— Router 需挂载,不自行监听。(p.14、17) - False —
app.use('/api', fn) is equivalent to app.get('/api', fn).— 前缀 middleware 与 method route 不同。 - False —
req.params contains query parameters and JSON body fields.— 输入来源分开。(p.15) - False —
req.query.page is guaranteed to be a Number.— 不保证。(p.15) - False —
req.path includes the query string.— 不包括。(p.15) - False —
req.baseUrl is always the complete absolute URL.— 是挂载路径。(p.15) - False —
req.xhr reliably proves that a request was made by fetch.— 只是检查特定头。(p.15) - False —
req.ip is always independent of proxy configuration.— trust proxy 会影响。(p.15) - True —
The regex route accepts POST /commits/main..dev.— 两捕获组。(p.14、17) - False —
The same regex accepts a hyphen in the branch name through \w+.—-不属于此处 word characters。 - False —
The fallback string HEAD changes the HTTP method.— 只是缺省终点文本。 - False —
Non-capturing groups consume numeric req.params capture positions.—(?:...)不捕获。
Response / Errors / Database Extension
- False —
res.cookie reads cookies sent by the client.— 设置响应 Cookie。(p.16;修正) - False —
Signed cookies are encrypted cookies.— 签名不是加密。 - False —
res.status(404) completes the response.— 只设状态。(p.16) - True —
res.sendStatus(404) sends a status response.— 不同于 status。(p.16) - False —
res.location('/x') performs a redirect by itself.— 只设 Location。(p.16) - False —
res.attachment('x.csv') automatically creates and sends a CSV file.— 只配置头。(p.16) - False —
res.get reads a request header.— 读取响应头;请求头用 req.get。(p.16) - False —
res.jsonp and res.json always produce the same response format.— JSONP 可包装 callback。(p.16) - False —
res.render always sends HTML even when a callback is supplied.— callback 用法需自行决定发送。(p.16;补充) - False —
Every asynchronous error is automatically handled in every Express version.— 需区分 4 / 5 与异步来源。(补充) - False —
A normal 404 automatically invokes custom error middleware.— 未匹配本身不等于抛 Error。 - False —
Defining a Mongoose Schema inserts a document.— 只是定义结构。(扩展) - False —
new Task(data) necessarily saves data to MongoDB.— 需 save / create。(扩展) - False —
Native driver find returns an array immediately.— 返回 cursor。(扩展) - False —
Mongoose updateOne returns the updated task document.— 返回写入结果。(扩展) - False —
A valid ObjectId format guarantees that a matching document exists.— 格式与存在性不同。(扩展)
5. Exam Quick Reference(考前速查)
- Native req / res: IncomingMessage / ServerResponse。(p.4–5)
- JSON body ≠ JSON header;Content-Length 要字节数。
- express() 建 app;use 挂处理;get/post 注册接口;listen 开端口。
- Pipeline: static → logger → JSON → URL-encoded → route。(p.7–13)
- Static 先响应 → 后面 logger 可能不执行。
- next ≠ return;send / json 不自动退出 JS 函数。
- Body parser: 匹配类型后填 req.body;不解析所有格式。
- extended: 嵌套 URL-encoded,不是 JSON 开关。
- Router: 创建 → 定义 route → app.use('/prefix', router)。
- Input: params 路径;query 查询;body 正文;cookies Cookie。
- Regex:
\w+不含连字符;(?:...)不捕获;HEAD是默认字符串。 - Response: status/set/cookie/location 不单独完成;send/json/end 通常完成。
- Cookie 修正: res.cookie 设置;req.cookies 读取;signed 非加密。
- Error handler:
(err, req, res, next);Express 4 async 常需 wrapper。 - Mongo 扩展: MongoDB 数据库;driver cursor;Mongoose Schema → Model → Document/Query。
- Startup: connect DB → create HTTP server → listen。
Lecture 20 — Templates, On the Server
本章实际只有 5 页。p.2 提到 extended example / in-class exercise,但 PDF 没有附更多页面;以下不将未提供的课堂代码当成课件内容。
1. Core Concepts(核心概念)
Template-based HTML Generation(模板生成 HTML)
A template combines reusable markup structure with data to generate HTML.(p.3–4)
课件列出的动机:
- 手写 HTML 冗长。
- 页面结构和内容经常重复。
- 用 JS 逐个创建 DOM 很繁琐。
- 全部交给客户端处理,可能拖慢用户看到响应的时间。
【课件限定】These are motivations, not universal performance guarantees.
- 服务端模板不保证所有应用、所有请求都更快。
- HTML 并非所有元素都必须有结束标签;课件 “requires end-tags” 是概括,HTML 有 void elements 等例外。
- 模板减少的是编写和复用成本,不表示生成结果不再是 HTML。
Client-side vs. Server-side Templates(客户端与服务端模板)
Template languages can be used on both the client and the server.(p.4)
- 客户端:浏览器执行模板生成逻辑,再更新 DOM。
- 服务端:服务器用模板和参数生成 HTML,发送给客户端。
- 服务器模板不需要服务器拥有浏览器 document DOM。
- Server-side rendering does not imply zero client-side JavaScript. — 服务端模板页面仍可加载脚本并交互。
- 一个应用可同时使用服务端模板与客户端逻辑。
Request-to-HTML Flow(请求到 HTML 的流程)
课件 p.4 图示逻辑:
- 请求进入 Express pipeline。
- Path handler 匹配请求。
- Handler 准备模板参数。
- Template engine 读取模板并结合参数生成 HTML。
- Express 把结果作为响应发送。
Template data is supplied by the server-side handler.
- 图中的 Params 指模板渲染参数,不应直接等同于
req.params。 - 参数可以来自数据库、应用计算或经过验证的请求输入。
- 浏览器通常收到生成的 HTML,不是必须先下载 Pug 再自行编译。
Express View Configuration(模板配置)
课件 p.5:
javascript
app.engine('pug', require('pug').__express);
app.set('views', path.join(__dirname, './views'));Two different responsibilities:
app.engine():注册扩展名与渲染函数的对应关系。app.set('views', ...):指定模板查找位置。
【补充】Default view engine is a separate setting.
javascript
app.set('view engine', 'pug');- 指定后可写
res.render('landing', data)。 - 课件写
res.render('landing.pug', data),已给扩展名;因此没有设置默认 view engine 并不必然导致该调用失败。 - 对遵循
__express约定的引擎,Express 可以自动加载;不一定必须同时手工 app.engine。 - 注册引擎、设置目录、实际渲染是三种动作,不能混淆。
Express-compatible engine callback contract(补充):
javascript
engine(filePath, options, callback)- filePath:模板路径。
- options:渲染数据与选项。
- callback:报告错误或生成 HTML。
- 该 callback 风格不表示模板计算本身必然在其他线程执行。
参考:Express — Template Engines、Pug — Express Integration。
Pug Syntax(Pug 语法)
课件模板:(p.5)
pug
html(lang="en")
head
title!= title
body
h1!= message- Indentation defines nesting. — 缩进决定嵌套层级。
html、head、title、body、h1是标签。(lang="en")是属性。- 不需要像 HTML 那样写配对结束标签。
title标签与右边变量title是不同角色。message是 handler 传入的模板变量。- 模板没有
doctype html,不能假设输出自动带<!DOCTYPE html>。
参考:Pug — Tags。
Escaped vs. Unescaped Output(转义与不转义)
The slide’s != operator outputs an expression without HTML escaping.(p.5)
这是本章最有考试价值的语法细节。
| 写法 | 含义 |
|---|---|
h1= message | 输出表达式,HTML 转义 |
h1!= message | 输出表达式,不做 HTML 转义 |
p Hello #{name} | 文本中的转义插值 |
p Hello !{name} | 文本中的不转义插值 |
【补充】用 message = '<em>Hello</em>' 判断输出:
h1= message:页面显示字面的<em>Hello</em>文本。h1!= message:em被当成标记,显示强调内容。- 不转义输出用户输入可能产生 HTML 注入 / XSS。
- 课件使用固定字符串
'Hey'、'Hello, world!',本例没有表现出恶意输入,但不能据此推断!=会自动清洗内容。 - 这里的
!=是 Pug 语法,不是 JavaScript 的不等比较操作。
Render Behavior(渲染行为)
课件 handler:(p.5)
javascript
app.get('/foo', (req, res) => {
res.render('landing.pug', {
title: 'Hey',
message: 'Hello, world!',
});
});Expected result:
/foo是请求 URL。landing.pug是服务器上的模板名称。- 浏览器不需要请求
/landing.pug才能看到页面。 - title 输出
Hey。 - h1 输出
Hello, world!。 - 这次 render 的 locals 不会自动变成所有请求共享的全局数据。
- 默认无 callback 的 res.render 会把生成内容发送给客户端。
- 不再需要紧接着
res.send()重复发送响应。
2. Comparisons & Distinctions(易混淆概念对比)
| 对比 | A | B |
|---|---|---|
| Template vs. output | Pug:模板源码 | HTML:生成结果 |
| Client vs. server rendering | 浏览器生成 / 更新页面 | 服务器生成 HTML 后返回 |
app.engine vs. app.set('views') | 注册渲染函数 | 设置查找目录 |
view engine vs. views | 默认引擎 / 扩展名 | 模板目录 |
| Route path vs. view name | /foo | landing.pug |
| Template locals vs. route params | { title, message } | req.params.id |
= vs. != | 转义输出 | 不转义输出 |
res.render vs. res.sendFile | 模板 + 数据生成内容 | 发送现有文件 |
Three similar-looking Pug lines:
| 写法 | 结果 |
|---|---|
h1 message | 静态文字 message |
h1= message | 读取变量 message 并转义输出 |
h1!= message | 读取变量 message,不转义输出 |
3. APIs & Configurations(API 与配置速查)
课件 API(p.5)
require('pug')— 加载 Pug 包,需先安装;不是 Node 内建模块。require('pug').__express— Express-compatible 模板渲染函数。app.engine('pug', require('pug').__express)— 注册.pug扩展名的引擎,返回 app;不马上渲染页面。app.set('views', path.join(__dirname, './views'))— 指定模板目录,不是静态资源目录。path.join(__dirname, './views')— 同步构造路径字符串,不读取模板、不创建目录。app.get('/foo', handler)— 注册 GET route,实际收到请求时才执行 handler。res.render('landing.pug', { title: 'Hey', message: 'Hello, world!' })— 查找并渲染模板,默认发送生成 HTML,不返回一个可直接当 HTML 使用的同步字符串。
必要补充
npm install pug— 安装模板引擎。const path = require('node:path')— CommonJS 导入路径模块。app.set('view engine', 'pug')— 指定默认引擎,允许 render 时省略.pug。res.render('landing', locals, callback)— 通过 callback 获取错误或 HTML,需自行决定如何发送。res.locals.title = 'Hey'— 当前请求的模板变量。app.locals.siteName = 'CS 4288'— 应用级模板变量,生命周期比单请求长。
Pug Syntax Quick Reference
html(lang="en")— html 标签带 lang 属性。head— head 标签,子节点通过缩进表示。body— body 标签。title!= title— title 标签内部输出 title 变量,不转义。h1!= message— h1 内输出 message,不转义。h1= message— 【补充】转义输出,更适合普通不可信文本。doctype html— 【补充】显式生成 HTML5 doctype。
【编程题扩展】最小 Express + Pug 连线
题目让你“返回一个模板页面”,按这条线写:安装引擎 → 设置目录 / 默认引擎 → 路由传数据 → render。
服务器 server.cjs:
javascript
const express = require('express');
const path = require('node:path');
const app = express();
// 设置后,res.render('landing') 可以省略 .pug。
app.set('view engine', 'pug');
// server.cjs 同级的 views 目录。
app.set('views', path.join(__dirname, 'views'));
app.get('/foo', (req, res) => {
// query 是用户输入;这里只接受字符串,否则使用默认值。
const name =
typeof req.query.name === 'string'
? req.query.name
: 'world';
res.render('landing', {
title: 'Hey',
message: `Hello, ${name}!`,
});
});
app.listen(8080, () => {
console.log('HTTP listening on 8080');
});模板 views/landing.pug:
pug
doctype html
html(lang="en")
head
title= title
body
h1= message- 此处用
=,让 query 带来的内容按文本转义。 - 不需要把 views 目录用 express.static 暴露出去才能 render。
- 服务器渲染完发送的是 HTML,Pug 源文件仍留在服务器。
- 如果接前面的数据库题:先
await Model.find(...),再res.render(view, { items }),不要把尚未执行的 Query 当作最终数据传入。
4. True / False Traps(判断题陷阱)
- True —
Templates can be used on both the client and the server.— 课件明确。(p.4) - False —
A server-side template requires the server to have a browser DOM.— 模板生成字符串不需要浏览器 DOM。(补充) - False —
Server-side templates always make every application faster.— 课件只是指出客户端全做可能更慢。(p.3;限定) - False —
Every HTML element requires a closing tag.— 有 void elements 等例外。(p.3;限定) - True —
A path handler can pass data to a template engine.— p.4 图示。 - False —
Params in the template-generation diagram must mean req.params.— 指渲染参数,不限定来源。(p.4) - False —
app.engine immediately renders a page.— 注册引擎。(p.5) - False —
app.set('views', ...) specifies the static-file directory.— 设置模板目录。(p.5) - False —
The views setting selects the default template language.— 默认引擎用 view engine。(p.5;补充) - False —
res.render must fail without view engine even when the view has a .pug extension.— 可按明确扩展名选择引擎。(p.5) - False —
Pug's != operator escapes HTML.— 不转义。(p.5) - False —
Pug's != is a JavaScript inequality test in this context.— 是模板输出操作符。(p.5) - True —
Indentation determines nesting in Pug.— 缩进是结构。(p.5) - False —
h1 message and h1= message both read the message variable.— 前者是静态文本。(补充) - False —
Unescaped template output automatically sanitizes user input.— 可能产生注入 / XSS。(补充) - False —
The route /foo requires the browser to request landing.pug directly.— 路由地址与模板文件名不同。(p.5) - False —
res.render always returns the final HTML string synchronously.— 按渲染流程 / callback 处理。(p.5;补充) - False —
A res.render callback always causes Express to send the HTML automatically.— callback 用法需自行发送。(补充) - False —
The slide's Pug template automatically includes an HTML5 doctype.— 没有写 doctype。(p.5) - False —
Server-rendered pages cannot use client-side JavaScript.— 两者可以组合。(补充)
5. Exam Quick Reference(考前速查)
- Template = structure + data → HTML。(p.3–4)
- Flow: request → pipeline → handler → template + locals → engine → HTML response。(p.4)
- Client / server 都可用模板,服务器模板不需要 document DOM。
- Pug: 缩进决定嵌套,括号写属性。(p.5)
app.engine('pug', fn):注册引擎。app.set('views', dir):模板目录。app.set('view engine', 'pug'):默认引擎。res.render(view, locals):生成并通常发送 HTML。- 明确
.pug扩展名时,不一定必须配置默认 view engine。 =转义;!=不转义;普通用户文本优先转义。/foo是 URL;landing.pug是服务端模板文件。- Params 图示是模板参数,不专指 req.params。
- render callback → 自行处理 err / html,不自动再发。
- 课件没有 doctype;不会凭空自动补出 HTML5 doctype。
Lecture 21 — MongoDB
本章 PDF 共 81 页,页码包含标题页;已检查文字、图示及终端截图。
【课件修正】:课件存在语法错误、概念简化或旧版本行为。【补充】:准确理解所需知识。【编程题扩展】:根据课件组织的服务端例题。
代码题范围判断:课件包含 CRUD、索引、aggregation、Map-Reduce 的代码片段;没有 Express / Mongoose 完整服务。最值得准备的综合题是“查询过滤 + projection + 更新 + 索引 + 分组统计”。
1. Core Concepts(核心概念)
Document Database(文档数据库)
MongoDB stores documents in collections.
MongoDB 以 collection 组织 document,文档由 field–value pairs 构成。(p.3–4、8)
- Database → Collection → Document → Fields — 数据库、集合、文档、字段。
- Documents are stored using BSON. — 不是把普通 JSON 字符串原样当作全部存储格式。
- Documents in one collection need not have identical fields or field types.
- A document may contain nested documents and arrays.
- 集合中的文档共用集合级别的索引定义,不是每条文档各自定义一套索引。
- Maximum BSON document size: 16 MiB. — 课件写 16 MB,精确表述为 16 MiB;限制针对单个文档,不是整个集合。(p.8)
- 嵌入的子文档、数组也计入父文档大小。
NoSQL categories listed in the slides(p.4):
| 类型 | 课件例子 | 识别点 |
|---|---|---|
| Key–value | Dynamo | 键对应值 |
| Column-family / wide-column | HBase | 课件写 columnar/tabular;不宜直接等同分析型列式存储 |
| Document | MongoDB | 可嵌套的结构化文档 |
Flexible Schema ≠ No Schema Design(灵活结构不等于不用建模)
MongoDB has a flexible schema, but applications still need a data model.(p.8、31–33)
- 不必预先固定所有文档相同的字段集合。
- 新字段通常不要求先执行关系表式的
ALTER TABLE。 - 不代表字段类型和业务关系可以随意混乱。
- 【补充】MongoDB can enforce schema validation when configured.
- Mongoose Schema 是应用侧建模机制;它与 MongoDB 服务器端 validation 不是同一层。
- 存进数据库的文档不是原 JS 对象引用;程序修改内存对象,不会自动修改数据库。
- 数据库提供持久化、查询、索引与并发控制,不只是“把对象留在内存里”。
MongoDB vs. SQL:课件表述的边界
课件强调灵活结构、嵌入、数据局部性和水平扩展。(p.5、14、30、42、46)
应记住的核心:
- MongoDB 可将相关信息嵌入同一文档,减少额外查询 / join。
- 文档结构可更接近应用里的对象结构。
- 反规范化可能改善一起访问的数据的 locality。
- 关系可以用 embedding 或 references 表达。
【课件限定】不要背成绝对结论:
- “SQL databases cannot scale” — 不准确。
- “All joins are slow” — 不准确,取决于数据、索引和执行计划。
- “MongoDB never needs joins” — 不准确。
- “A primary key is literally a memory address” — p.42 是类比;主键是稳定的逻辑标识,不是实际进程内存地址。
- 【补充】MongoDB supports join-like aggregation through
$lookup. — 不是本课主要 API,但足以否定“MongoDB 完全不能 join”。
CAP — Consistency, Availability, Partition Tolerance
课件将 MongoDB 归为 CP。(p.3)
- C — Consistency: 在 CAP 语境中强调一致的读取语义。
- A — Availability: 请求能得到响应的可用性要求。
- P — Partition tolerance: 面对节点间网络分区。
【课件限定】CP is a classification, not a guarantee that every MongoDB read is always the newest value.
- 网络分区时,一致性与可用性存在取舍。
- MongoDB 的具体读写保证受 read preference、read concern、write concern 等设置影响。
- 从异步复制的 secondary 读取可能看到旧数据。
- 高可用设计不代表故障期间绝对没有写入中断。
- p.3 的 “automatic scaling” 是能力概括,不表示任意单机安装会自动变成分片集群。
JSON vs. BSON(格式与类型)
JSON is a text-based data-interchange format; BSON is a binary serialization format for JSON-like documents.(p.9–12)
JSON:
- JavaScript Object Notation。
- 支持 name–value pairs、数组与嵌套。
- JSON 数据不是可执行 JS 代码。
- 严格 JSON 与 JS 对象字面量并不相同。
BSON:
- 课件称 Binary JSON。
- 支持比普通 JSON 更丰富的类型,例如 ObjectId、Date、不同数值类型、binary data。
- 设计目标:lightweight、traversable、efficient encoding / decoding。
- BSON does not mean compressed JSON. — 二进制编码不保证比同一内容的 JSON 文本更小。
- 存引用值不意味着数据库自动建立外键约束或自动展开关系。
- p.11 的“BSON Example”是人可读的文档示意,不是实际 BSON 二进制;缺逗号、弯引号等也不能直接当合法 JSON 执行。
BSON Types & $type(类型识别)
课件完整类型表:(p.12)
| BSON type | 课件编号 | 常见用途 / 限定 |
|---|---|---|
| Double | 1 | 浮点数 |
| String | 2 | 字符串 |
| Object | 3 | 嵌入文档 |
| Array | 4 | 数组 |
| Binary data | 5 | 二进制 |
| ObjectId | 7 | 常见默认 _id 类型 |
| Boolean | 8 | 布尔值 |
| Date | 9 | 日期时间 |
| Null | 10 | 显式 null |
| Regular Expression | 11 | 正则 |
| JavaScript | 13 | 历史 BSON code 类型,不代表任意字符串自动执行 |
| Symbol | 14 | 已弃用类型 |
| JavaScript with scope | 15 | 已弃用类型 |
| 32-bit integer | 16 | Int32 |
| Timestamp | 17 | 与普通 Date 不同,常用于内部时间标记 |
| 64-bit integer | 18 | Int64 / Long |
| MinKey | 255 | 课件写法;查询类型编号应使用 -1 或 "minKey" |
| MaxKey | 127 | 特殊排序边界类型 |
【课件修正】MinKey 的 BSON 类型字节可对应 0xFF,但不能因此把 $type: 255 当成现代查询的标准写法。
$type可按类型编号或别名查询。- 现代 BSON 还有课件未列出的类型,例如 Decimal128;课件表不是所有版本的完整清单。
- Date ≠ Timestamp。
- String
"123"≠ Number123≠ ObjectId。
_id & ObjectId(主键与对象标识)
For ordinary collections, _id identifies a document and must be unique within the collection.(p.13)
_id是不可变标识。- 通常自动建立唯一
_id索引。 - 不提供
_id时,常由 driver / shell 自动生成 ObjectId。 _id不必须是 ObjectId:课件 ZIP 示例使用字符串或数字。- 不要求跨所有集合全局唯一。
- 【课件修正】“Any non-array type” is incomplete. —
_id也不能使用 regex、undefined 等不允许的类型。
ObjectId:
- 12 bytes;常显示为 24 个十六进制字符。
- 包含生成时间信息。
- 排序大致接近生成时间顺序。
- Roughly ordered does not mean perfectly chronological.
- 不保证跨进程、同一秒内或时钟不同的客户端严格按创建先后排序。
- 默认生成的 ObjectId 不等于业务上绝对无冲突的数学证明,唯一索引仍有职责。
- 字符串
"507f..."与 BSONObjectId("507f...")不是相同类型。
参考:MongoDB — Documents、BSON Types。
mongod vs. mongo vs. mongosh vs. mongos
课件安装和 shell 示例:(p.16–18)
| 名称 | 职责 |
|---|---|
mongod | 数据库服务器进程 |
mongo | 课件使用的旧交互 shell |
mongosh | 当前常用交互 shell |
mongos | 分片集群的查询路由进程 |
mongodb npm package | Node.js 官方 driver |
mongoose npm package | ODM,应用侧 Schema / Model 等抽象 |
- shell 是数据库客户端,不是数据库服务器。
mongos不是mongosh的缩写。- 课件 Windows 安装目录和命令属于旧安装流程,不要求所有 OS 使用同一路径。
Shell Database Selection(选择数据库)
课件:(p.18)
db:查看当前数据库。show dbs:列出数据库。use name:切换当前数据库上下文。show collections:查看当前数据库集合。
Selecting a database does not by itself persist a new database.
use newdb不等于立即创建有数据的数据库。- 课件说“插入后才创建”,重点是 lazy creation。
- 【补充】显式创建集合等操作也可使数据库实际建立,不只有 insert 一条路径。
CRUD — Create, Read, Update, Delete
Insert(插入)
课件使用旧方法 insert()。(p.19–20)
- 一个文档对象:插入一条。
- 文档数组:插入多条。
- 集合不存在时,普通写入可隐式创建集合。
- 允许新增此前其他文档没有的字段,前提是没有 validation 等约束禁止。
- p.20 示例缺少闭合括号,不能直接照抄。
- 【补充】现代代码优先明确使用
insertOne()/insertMany()。
Find & Cursor(查询与游标)
find() returns a cursor; findOne() returns one document or null.(p.21)
find()不是立即返回全部文档的普通数组。- 课件 shell 默认显示前 20 条,是显示 / 批次行为,不是查询只能匹配 20 条。
.limit(n)显式限制结果数量。- 没有排序,不应依赖固定顺序。
findOne()在多个匹配项中取一条,不保证是“最新”或“最早”。- Node driver 中需要异步读取 cursor,例如
.toArray()。 - 【补充】
limit(0)通常表示不施加数量上限,不是返回零条。
Filters — AND, OR, IN(过滤条件)
课件:(p.22–23)
{ state: 'TN', city: 'NASHVILLE' }:隐式 AND。{ $or: [{ state: 'TN' }, { state: 'CA' }] }:OR。{ state: { $in: ['TN', 'CA'] } }:同一字段多个候选值。
【课件修正】p.23 的 $or 数组缺少每个条件的对象括号,$in 后缺冒号。
正确:
javascript
{ $or: [{ state: 'TN' }, { state: 'CA' }] }
{ state: { $in: ['TN', 'CA'] } }$or的数组元素是完整条件对象。- 同一 JS 对象中重复写相同字段,不会自动构成 OR;后面的属性可能覆盖前面。
Projection(返回字段选择)
The first argument filters documents; the second argument projects fields.(p.24)
javascript
db.zips.find({ state: 'TN' }, { city: 1, pop: 1, _id: 0 });- filter:哪些文档。
- projection:返回哪些字段。
1:包含字段。0:排除字段。_id默认通常保留。- inclusion 与 exclusion 通常不能随意混用,排除
_id是常见例外。 - projection 不删除数据库中原字段。
- p.24 的 SQL 对照字段与上下示例有不一致,应按 Mongo projection 本身理解。
$exists(存在性)
$exists: true includes fields whose value is null.(p.24,边界补充)
{ f: { $exists: true } }:有字段 f,包括f: null。{ f: { $exists: false } }:没有字段 f。- 不等于判断值是否 truthy。
- 【补充】
{ f: null }通常匹配显式 null 或字段缺失,不等于只匹配存在且为 null。
Update vs. Replace(修改字段与替换文档)
课件 p.25–26 混用了新旧方法,属于重点纠错区。
updateOne() updates at most one matching document.
$set修改 / 新增指定字段。$unset移除字段。updateMany()才用于更新所有匹配项。- 【课件修正】
updateOne(..., { multi: true })不会因此变成 updateMany。 upsert: true:没有匹配项时可插入新文档。- 默认未匹配时不自动插入。
replaceOne() replaces a matching document’s non-_id contents.
- replacement 中没写的旧字段会消失。
- 原
_id仍需保留 / 不可改成不同值。 - 【课件修正】不能把不带
$操作符的普通 replacement 文档传给现代 updateOne,来实现课件所述整体替换。应使用 replaceOne。
参考:MongoDB — updateOne、replaceOne。
Delete(删除)
课件:(p.27)
deleteOne(filter):最多删除一条。deleteMany(filter):删除全部匹配项。- filter
{}:没有过滤条件。 deleteMany({})清空文档,但不是 drop collection,索引 / 集合本身通常仍在。- 【课件修正】
deleteOne(filter, true)混入旧 remove 的 justOne 风格;现代第二参数应是 options 对象,不需要 true 才删一条。
Atomicity & Isolation(原子性与隔离)
A single-document write is atomic, even when it changes multiple fields.(p.28)
- 单次对一个文档的修改,不会让其他操作看到只改了一半的该次写入。
updateMany()不代表整个匹配集合作为一个整体自动原子更新。- 一个业务流程中的“先查再改”两步,也不因为都操作同一文档就自动成为一个原子操作。
- 【补充】可把预期旧状态放入更新 filter,避免部分竞争问题。
- 现代 MongoDB 支持多文档事务,不能背成“永远不支持事务”。
【过时内容】$isolated is not a modern transaction mechanism.
- p.28 的
$isolated: 1是旧版本隔离机制。 - 不要在当前服务代码中照抄。
- 不等于提供事务的完整原子性、回滚、跨文档一致性。
参考:MongoDB — Atomicity and Transactions。
Embedding vs. Linking(嵌入与引用)
Model data around how the application accesses it.(p.33–40、46)
Embedding:
- 相关信息放在同一文档。
- 类似预先把相关数据放到一起。
- 一起读取方便,单文档更新便于利用原子性。
- 可能带来重复信息、文档增长和更新多份副本的成本。
- 受 16 MiB 单文档限制。
- 不适合把无限增长的子项不加控制地全部塞入父文档。
Linking / referencing:
- 在文档中保存另一文档的标识。
- 数据可独立读取和更新。
- 更灵活,减少共享实体的重复存储。
- 需要额外查询、应用连接或
$lookup等机制。 - 引用不会自动变成数据库强制外键,也不会自动级联删除。
Relationship Examples(关系建模)
One-to-one(p.35)
- ZIP 与 council person。
- 可以在 ZIP 中嵌入 council_person。
- 也可以单独放 council person,并保存 zip_id。
- 关系类型本身不决定只能用一种写法。
One-to-many(p.37–39)
- 一个 publisher 对应多本 book。
- Embedding 示例:每本 book 内嵌 publisher 信息。
- Linking 示例:book 存
publisher_id: 'oreilly',publisher 单独保存。 - 如果 publisher 信息变化,嵌入多本 book 的副本可能都需要更新。
Many-to-many(p.40–41)
- book 内嵌作者摘要数组。
- author 集合保存完整作者信息。
- 这是可以混合 embedding 与 references 的例子。
- 根据读取方式决定关系放哪边,不要求所有关系都建“中间表”。
Dot notation(嵌套路径):
javascript
db.books.find({ 'authors.name': 'Kristina Chodorow' });- 可匹配 authors 数组中某个对象的 name。
- 【课件修正】作为 JS 对象键时,
authors.name要加引号。 - 【补充】多个数组子字段条件不一定落在同一个数组元素上;要求同一元素时需考虑
$elemMatch。
Checkout Modeling(借书示例,p.43–45)
课件规则:
- 同一本书同一时刻只能被一个学生借走。
- 一个学生可以借多本书。
- student 中保存 checked_out 数组,每个元素包含 book ID 和借出时间。
【补充】The document shape alone does not enforce every business constraint.
- 不同 student 文档各自存同一本书,不会仅因这份示例结构就自动禁止。
- 跨文档唯一性 / 并发借阅需额外设计。
- “示例表达了关系”与“数据库自动强制所有业务规则”是两件事。
Indexes(索引)
Indexes store selected field values in a structure that helps locate documents efficiently.(p.48–50)
- 没有可用索引时,过滤查询可能需要 collection scan。
- 有索引不代表该查询一定选择它。
- 选择性很差、需要取大量文档时,索引不一定更快。
- 索引也占空间,写入时需要维护。
- 建索引不会改变原文档字段值。
- 默认
_id索引不等于所有字段都已索引。
Index directions:
1:ascending。-1:descending。- 建索引的方向不是 projection 的包含 / 排除标记。
Index Types(索引类型)
Single-field index(p.51)
javascript
{ score: 1 }一个字段。
Compound index(p.52)
javascript
{ userid: 1, score: -1 }- 一个包含多个字段的索引,不等于两个独立索引。
- 先按 userid,再在相同 userid 内按 score 降序。
- 字段顺序重要。
- 【补充】前缀能力很重要:
{ state: 1, city: 1 }与{ city: 1, state: 1 }不应认为完全等价。 - 不要把“后缀字段单独查询”简单说成绝对不能用索引;准确说法是通常不能获得与合适前缀同样的高效定位能力。
参考:MongoDB — Compound Indexes。
Multikey index(p.53)
- 索引字段包含数组值时,MongoDB 自动形成 multikey index。
- 数组多个元素可贡献多个索引项。
- 课件
addr是地址文档数组,对'addr.zip'建索引。 - 【课件修正】键名应写
'addr.zip',不能把未加引号的点路径当 JS 对象键。 - 嵌套字段不必然是数组,因此“有点路径”不等于“必然 multikey”。
- 多字段 compound 与数组 multikey 是两个不同维度,不是同义词。
- 课件 loc 是经纬度数组,普通
{ loc: -1 }是数组索引示例,不自动等于 geospatial index。
参考:MongoDB — Multikey Indexes。
Index Management, Hint & Explain(索引管理与执行分析)
课件使用 ensureIndex()。(p.50–61)
- 当前常见写法:
createIndex()。 getIndexes():查看定义。dropIndex():删除指定索引。dropIndexes():删除可删除的非_id索引。hint():明确指定索引,覆盖通常的优化器选择。explain():查看执行计划 / 信息。
Hint is not a sorting contract.
- p.57–59 的 hint 示例看起来按索引顺序输出。
- 如果业务要求排序,应明确
.sort(...),不要依赖未声明的返回顺序。 - 指定索引不保证一定更快,也不代表自动创建这个索引。
Screenshot result comparison(p.60–61):
查询 Nashville / TN:
- 无相关索引:返回 19 条,但扫描约 29,467 条。
- 有复合索引:同样返回 19 条,扫描约 19 条。
- Index changes work performed, not the logical matching condition.
旧截图字段:
| 旧字段 | 含义 / 现代对应理解 |
|---|---|
cursor: BasicCursor | 旧版 collection scan 表达 |
BtreeCursor ... | 旧版索引扫描表达 |
n | 返回数量 |
nscannedObjects | 扫描文档数量 |
nscanned | 旧版扫描计数,不能不加区分当成现代某个字段 |
isMultiKey | 是否 multikey |
indexOnly | 是否仅靠索引完成旧版执行 |
indexBounds | 扫描边界 |
millis | 执行时间 |
【补充】现代常查:COLLSCAN / IXSCAN、nReturned、totalDocsExamined、totalKeysExamined。
- 默认 explain 不保证包含完整执行统计。
- 需要实际执行统计时常用
"executionStats"。 indexOnly: false表示使用索引后仍可能读取文档,不是“有索引就完全不读文档”。
参考:MongoDB — Explain、createIndex。
Aggregation(聚合)
Aggregation processes documents and returns computed results.(p.62)
- 可分组、求和、求平均、排序、转换字段等。
- 在 mongod 中处理,减少应用拿回全部原始数据后再计算的需要。
- 不代表数据库计算没有资源成本。
- 普通统计 pipeline 不修改原集合。
- 【补充】包含
$out/$merge等写入 stage 时例外。
Aggregation Pipeline(聚合管线)
Stages process the output of previous stages in sequence.(p.63–65、70–71)
$match:过滤文档。$group:分组聚合。$project:选择、重命名或计算输出字段。$sort:排序。$skip:跳过前 N 条。$limit:保留最多 N 条。- pipeline stage 可以按需要重复。
- 一条输入文档不必对应一条输出文档。
- 过滤可减少文档数量,分组可把多条合成一条,其他转换也可改变形状。
- stage 顺序有意义,不能任意交换。
$group不自动排序结果。
"$field" vs. "literal":
'$pop':读取当前文档 pop 字段。'pop':普通字符串。$group: { _id: '$state' }:按每条文档的 state 分组。$group: { _id: 'TN' }:所有输入使用同一个常量组键 TN。- group 结果中的
_id是组键,不是自动保留输入文档主键。
参考:MongoDB — Aggregation、$group、$project。
Aggregation Example(课件整段代码,p.64)
课件意图是统计 TN 的人口总和。下面采用现代 pipeline 数组写法:
javascript
db.zips.aggregate([
{ $match: { state: 'TN' } },
{
$group: {
_id: 'TN',
pop: { $sum: '$pop' },
},
},
]);执行过程:
- 过滤掉 CA、NY。
- 保留 TN 的 Nashville
1579和 Memphis4144。 - 将 pop 相加。
- 得到
{ _id: 'TN', pop: 5723 }。
陷阱:
$sum: '$pop':加人口。$sum: 1:数文档。_id: 'TN'是常量;因为前面已过滤到 TN,所以这份例子成立。- 若删除 match 又保留
_id: 'TN',就会把全部输入汇总为一个仍叫 TN 的组。 - 想统计所有州,应改
_id: '$state'。
Aggregation Result Size(聚合结果限制)
【课件修正】The 16 MiB BSON limit is not a universal limit on the total size of all modern aggregation results.(p.66、71)
- 课件旧版本表格将 aggregate 输出描述为 inline,受整体 BSON 结果限制。
- 现代 aggregate 通常返回 cursor。
- 每个返回的结果文档仍受 16 MiB 限制。
- 不能因此认为全部结果加起来只能有 16 MiB。
- 内存 / 磁盘使用限制与单文档大小限制又是不同维度。
参考:MongoDB — Aggregation Pipeline Limits。
Map-Reduce(映射与归约)
课件:(p.66–67、70–72)
- Map: 处理输入文档并 emit key–value pairs。
- Reduce: 将相同 key 的 values 合并。
- Finalize: 可选的最后处理。
- 自定义 JavaScript 函数。
- 课件认为更灵活,但比 aggregation pipeline 更复杂、效率通常更低。
- 【课件修正】Map 不必每条输入至少 emit 一次,也可以不 emit 或 emit 多次。
- 【版本补充】MongoDB 5.0 起 Map-Reduce 已弃用,当前更适合使用 aggregation。
- 旧 inline 结果与写入输出集合的容量约束不同,不能把“可写很多结果”理解为单文档无限大。
Map-Reduce Example(课件完整片段,p.67、72)
javascript
db.zips.mapReduce(
function () {
emit(this.city, this.pop);
},
function (key, values) {
return Array.sum(values);
},
{
query: { state: 'TN' },
out: 'city_pop_totals',
}
);Read this code in business order:
query先保留 TN。- 每条 ZIP 文档 emit:city 为 key,pop 为 value。
- 按 city 合并。
- 输出到
city_pop_totals集合。
p.67 小样本:
- Nashville:
1579 + 612 = 2191。 - Memphis:
4144。 - 标准结果形式:
{ _id: 'NASHVILLE', value: 2191 }。 - 课件 Memphis 输出框写成
pop,与标准 Map-Reduce 输出字段value不一致。 - p.72 真数据的 Nashville
349822来自另一数据集,不与小样本结果冲突。 Array.sum()是课件旧执行环境中的 helper,不是浏览器 / Node 标准 JS Array API。- map 中
this表示当前输入文档;不能随意换箭头函数后假定 this 不变。 out可能写入 / 替换结果集合,不是纯粹无副作用的读取。- 这是数据库端 Map-Reduce,不是 JS 数组的
.map().reduce()。
Single-purpose Aggregation & Historical group
课件:(p.68–73)
- count:匹配文档计数。
- distinct:某字段的不同取值。
- 历史 group:按字段分组。
- 功能比通用 pipeline 更有限。
Distinct example:
javascript
db.zips.distinct('state');- 输出州值,例如
['CA', 'NY', 'TN']。 - 返回值是去重值,不是完整文档。
- 不要依赖示例中的值顺序。
【旧版本表格:识题即可】:
- aggregate:pipeline,stage 可重复,可过滤、变换和生成输出文档。
- mapReduce:自定义 map / reduce / finalize,可做增量式输出合并。
- 旧 group:支持字段 / keyf 分组、自定义 reduce / finalize。
- 旧 group 输出 inline,表中写最多 20,000 个分组,且不支持分片集合。
- aggregate / mapReduce 旧表中支持分片输入。
- 旧
groupcommand 与现代 pipeline 的$groupstage 不是同一个 API。 - 不应把旧 group 的限制、aggregate 的旧 inline 限制直接套在现代
$group上。
Replication(复制)
Replication keeps copies of the same data across members for redundancy and availability.(p.74–77)
课件目的:
- Fault tolerance。
- Availability。
- 可在合适读偏好下增加读容量。
Replica set members:
| Member | 课件职责 | 限定 |
|---|---|---|
| Primary | 接收应用读写,特别是写入 | 默认读取通常也走 primary |
| Secondary | 异步复制;符合条件可当选 primary | 不直接作为普通应用写入节点 |
| Arbiter | 参与投票,不能当 primary | 不保存数据副本 |
| Delayed secondary | 故意延迟应用复制,不能当 primary | 配置为 priority 0,可用于恢复误操作 |
- Replica set 正常最多有一个可写 primary。
- 故障选举期间可以暂时没有 primary。
- secondary 复制是异步的,可能落后。
- 读取 secondary 需相应 read preference 等配置,不是默认所有读自动分摊。
- Arbiter 不是“第三份数据备份”。
- secondary 也可能因配置为不可选举而不能晋升,不能说所有 secondary 必然可晋升。
- Delayed secondary 不能当 primary,不等于不能参与投票;取决于配置。
参考:MongoDB — Replica Set Members、Delayed Members。
Failover, Elections, Rollback & TLS(故障处理)
课件关键词:(p.77)
- Heartbeats: 检测成员状态。
- Elections: 选择新 primary。
- Automatic failover: primary 故障后自动选举接替。
- Odd number: 推荐奇数投票配置以避免无益的票数配置与平票问题。
- Rollback: 恢复成员上未进入最终复制历史的部分写入可能回滚。
- SSL/TLS: 保护节点 / 客户端间传输。
必要边界:
- 自动切换不代表写入始终零中断。
- 选举通常需要多数投票成员可达。
- “奇数成员”更准确关注 voting members;不是偶数总成员绝对非法。
- TLS 保护传输,不等于替代认证、授权或备份。
- 普通复制会传播误删除,因此 replication 不等于完整备份方案。
Sharding(分片)
Sharding partitions data across shards for horizontal scaling.(p.74、79)
- Replication:多份相同数据。
- Sharding:不同 shard 分担数据。
- 两者可以结合:每个 shard 可以是 replica set。
mongos是 query router,不是应用的 Express Router。- 图中 config servers 保存分片集群的配置 / 元数据。
- 由 shard key 决定数据分布与请求定位的重要依据。
- Range-based sharding:根据 key 的范围划分数据。
Shard key selection(p.79):
- Cardinality: 不同 key 值的数量。
- 过低基数限制有效分布能力。
- Hotspotting: 写入 / 访问集中到少数范围或 shard。
- 单调增长 key 在 range-based 分布下容易把新写集中到末端范围。
- 高基数不保证没有热点;还要看频率、单调性与查询方式。
- 查询缺少能定位 shard 的条件时,可能需要访问多个 shard。
- 不要把“自动扩展能力”理解成“选什么 shard key 都能均匀提速”。
参考:MongoDB — Choose a Shard Key。
2. Comparisons & Distinctions(易混淆概念对比)
Relational vs. Document Terminology(p.14、30)
| Relational | MongoDB | 注意 |
|---|---|---|
| Database | Database | 数据库 |
| Table | Collection | 类比,不代表完全相同约束 |
| Row / Tuple | Document | 文档可嵌套、字段可不同 |
| Column | Field | 字段可包含对象 / 数组 |
| Primary key | _id | _id 可使用自定义允许类型 |
| Foreign key | Reference | 不自动具有外键约束 |
| Join | Embedding / additional query / lookup | 嵌入减少 join,不等于只能嵌入 |
| Partition | Shard | 分布数据 |
| Index | Index | 两种模型都使用索引 |
JSON vs. BSON vs. JavaScript Object
| 项目 | JSON | BSON | JS object |
|---|---|---|---|
| 形式 | 文本 | 二进制序列化 | 运行时对象 |
| 丰富类型 | 类型有限 | ObjectId、Date、Int 等 | JS 运行时类型 |
| 是否数据库存储格式 | 不是 Mongo 的完整底层类型模型 | 是核心文档格式 | 不直接作为内存引用存进数据库 |
| 是否支持嵌套 | 是 | 是 | 是 |
| 是否可直接代表函数执行 | 否 | code 类型不等于自动执行 | 函数值取决于 JS 代码 |
CRUD Distinctions
| API / operator | 返回 / 效果 | 易错点 |
|---|---|---|
find | cursor | 不是数组 |
findOne | 一条或 null | 不等于最新一条 |
$set | 修改 / 添加字段 | 保留其他字段 |
$unset | 移除字段 | 不是设 null |
updateOne | 最多改一条 | multi:true 不变多条 |
updateMany | 改多条 | 非整体自动事务 |
replaceOne | 替换文档内容 | 未写旧字段消失,_id 不可改 |
deleteOne | 最多删一条 | 不需第二参数 true |
deleteMany | 删全部匹配 | {} 可清空文档 |
upsert:true | 无匹配时插入 | 默认不启用 |
| Projection | 改返回字段 | 不删除存储字段 |
Index Types
| 类型 | 例子 | 核心区别 |
|---|---|---|
| Single-field | { pop: -1 } | 一个字段 |
| Compound | { state: 1, city: 1 } | 多字段、有字段顺序 |
| Multikey | 对数组 loc 或 'addr.zip' 建索引 | 数组元素产生索引项 |
| Geospatial | 需相应地理索引类型 | 普通数组索引不自动成为地理索引 |
Aggregation Approaches(p.66–71)
| 项目 | Pipeline | Map-Reduce | 旧 group |
|---|---|---|---|
| 表达方式 | stages / expressions | JS map、reduce、finalize | 分组函数与配置 |
| 当前学习重点 | 高 | 识别旧代码 | 历史表格 |
| 输入输出数量 | 可改变 | key–value 聚合 | 分组结果 |
| 输出 | 现代常为 cursor | inline 或输出集合等 | 旧 inline 数组 |
| 是否自动修改原集合 | 普通统计不改 | out 可写结果集合 | 不当作现代通用方案 |
| 常见误区 | 把总结果限制成 16 MiB | 以为 Array.sum 是 JS 标准 | 与 $group stage 混淆 |
Replication vs. Sharding(p.74–79)
| 项目 | Replication | Sharding |
|---|---|---|
| 数据关系 | 同一数据的多份副本 | 不同数据分布到不同 shard |
| 主要目的 | 冗余、故障恢复、可用性 | 水平扩容、分担容量与负载 |
| 核心角色 | primary / secondary / arbiter | mongos / shards / config servers |
| 能否组合 | 是,每个 shard 可是 replica set | 是 |
| 自动解决全部性能问题 | 否 | 否 |
3. APIs & Configurations(API 与配置速查)
3.1 Shell & Process Commands(p.16–18)
mongod— 启动数据库服务器进程;不是进入交互 shell。mongo— 课件旧 shell 命令。mongosh— 【补充】当前 shell。mkdir data/mkdir data\db— 课件 Windows 数据目录准备命令,不是数据库查询。db— 查看当前数据库上下文。show dbs— 列出可见数据库。use blog— 切到 blog;单独执行不保证持久创建。show collections— 列出当前数据库集合。ISODate('2010-09-24')— shell 日期构造 helper;Node 普通 JS 常用new Date(...)。ObjectId('507f1f77bcf86cd799439011')— shell 构造 ObjectId;不是同值字符串。
3.2 Insert & Query(p.19–24、41、48)
db.zips.insert(doc)— 课件旧式插入接口;现代优先 insertOne / insertMany。db.zips.insertOne({ _id: '37201', city: 'NASHVILLE', state: 'TN', pop: 1579 })— 插入一条,返回含 insertedId 的结果;会写数据库。db.zips.insertMany([doc1, doc2])— 插入多个文档,返回多个 insertedIds;不要默认视为整体事务。db.zips.find()— 返回全部匹配文档的 cursor,不修改数据。db.zips.findOne({ state: 'TN' })— 返回一条匹配文档或 null。db.zips.find({ state: 'TN', city: 'NASHVILLE' })— 隐式 AND。db.zips.find({ $or: [{ state: 'TN' }, { state: 'CA' }] })— 多个条件 OR;修正课件语法。db.zips.find({ state: { $in: ['TN', 'CA'] } })— state 属于候选值集合。db.users.find({ score: { $lt: 30 } })— score 小于 30,不包含 30。(p.48)db.zips.find({ state: 'TN' }, { city: 1, pop: 1, _id: 0 })— 过滤 TN,只返回 city / pop。db.zips.find({}, { loc: 0 })— 返回其他字段,排除 loc。db.zips.find({ loc: { $exists: true } })— loc 存在,包括 null。db.zips.find({ loc: { $exists: false } })— loc 缺失。db.zips.find({ pop: { $type: 16 } })— 查询 BSON Int32 类型;也可用合适类型别名。db.books.find({ 'authors.name': 'Kristina Chodorow' })— 点路径查询嵌套数组对象字段;修正引号。db.zips.find().limit(20)— cursor 最多取 20 条,不代表原集合只有 20 条。db.zips.find().sort({ pop: -1, _id: 1 })— 【补充】人口降序,主键作为稳定次序。db.zips.find().skip(20).limit(10)— 【补充】查询游标分页;普通 find cursor 的 skip / limit 语义不要和 aggregation 的阶段顺序混淆。
3.3 Update, Replace, Delete(p.25–28)
db.zips.updateOne({ _id: '37201' }, { $set: { pop: 2000 } })— 最多改一条,其他字段保留;返回 matchedCount / modifiedCount 等写入结果。db.zips.updateMany({ state: 'TN' }, { $set: { reviewed: true } })— 修改所有匹配文档,不自动作为整个集合的一笔事务。db.zips.updateOne({ _id: '37201' }, { $unset: { reviewed: 1 } })— 移除 reviewed 字段;右侧 1 是惯用占位值,不表示删一条文档。db.zips.updateOne({ _id: '37201' }, { $set: { pop: 2000 } }, { upsert: true })— 无匹配时插入;检查 upsertedId。db.zips.replaceOne({ _id: '37201' }, { city: 'NASHVILLE', state: 'TN', pop: 2000 })— 替换非_id内容,遗漏旧字段消失。db.zips.deleteOne({ state: 'TN' })— 最多删一条,返回 deletedCount 等结果。db.zips.deleteMany({ state: 'TN' })— 删全部 TN 文档。db.zips.deleteMany({})— 清空集合文档,不等于 drop collection。$isolated: 1— 课件旧式内容,不作为当前代码推荐 API。
【补充】写入结果判断:
matchedCount === 0— 没匹配到。matchedCount === 1 && modifiedCount === 0— 可能匹配到了,但新值与旧值相同。deletedCount === 0— 没有删除文档,不必然代表数据库连接失败。upsertedId— upsert 新建文档的 ID。
3.4 Index APIs(p.50–61)
db.users.ensureIndex({ score: 1 })— 课件旧式创建索引;现代用 createIndex。db.users.createIndex({ score: 1 })— 创建单字段升序索引,返回索引名称。db.users.createIndex({ userid: 1, score: -1 })— 复合索引,先 userid 升序、再 score 降序。db.users.createIndex({ 'addr.zip': 1 })— 嵌套路径索引;addr 是数组时形成 multikey。db.zips.createIndex({ pop: -1 })— 对应 p.55 单字段 demo。db.zips.createIndex({ state: 1, city: 1 })— 对应复合 demo。db.zips.createIndex({ loc: -1 })— 对应数组字段 demo,不自动成为地理索引。db.users.getIndexes()— 返回索引定义,不是索引扫描后的业务结果。db.users.dropIndex({ score: 1 })— 删除指定索引,不删除 score 字段。db.zips.dropIndexes()— 删除可删除的非_id索引;不是删除 collection。db.zips.find().limit(20).hint({ pop: -1 })— p.57,指定人口索引扫描。db.zips.find().limit(20).hint({ state: 1, city: 1 })— p.58,指定复合索引。db.zips.find().limit(20).hint({ loc: -1 })— p.59,指定数组字段索引。db.zips.find({ city: 'NASHVILLE', state: 'TN' }).explain()— p.60–61,分析查询。db.zips.find({ state: 'TN' }).explain('executionStats')— 【补充】查看执行统计;此操作会实际执行查询分析,不修改业务文档。
3.5 Aggregation APIs(p.63–73)
db.zips.aggregate([stage1, stage2])— 顺序执行 pipeline;现代通常返回 cursor。{ $match: { state: 'TN' } }— 保留 TN 文档。{ $group: { _id: '$state', totalPop: { $sum: '$pop' } } }— 按州汇总人口。{ $group: { _id: null, count: { $sum: 1 } } }— 【补充】所有输入合成一组并计数。{ $sort: { totalPop: -1 } }— 按前面输出的 totalPop 降序。{ $skip: 10 }— 跳过当前阶段输入的前 10 条。{ $limit: 5 }— 保留当前阶段输入的前 5 条。{ $project: { _id: 0, state: '$_id', totalPop: 1 } }— 隐藏组键字段名_id,将其值作为 state 返回。{ averagePop: { $avg: '$pop' } }— 【补充具体语法】group 中计算平均值,对应 p.63 提到的平均计算能力。db.zips.distinct('state')— 返回不同州值数组,不返回完整文档。db.zips.countDocuments({ state: 'TN' })— 【补充现代方法】返回匹配数量;p.68 讲计数能力。db.zips.mapReduce(map, reduce, options)— 课件旧式 Map-Reduce;已弃用。emit(this.city, this.pop)— 旧数据库 map 函数发出 city / pop 键值。Array.sum(values)— 旧 Map-Reduce 环境 helper,不是标准 Array 静态方法。query: { state: 'TN' }— Map-Reduce 输入过滤。out: 'city_pop_totals'— 将结果写入指定集合。db.city_pop_totals.find({ _id: 'NASHVILLE' })— p.72,读取 Map-Reduce 结果。group/keyf/finalize— p.70–71 的历史比较术语;不要与现代$group混为一谈。
3.6 【代码大题】CRUD + Index + Aggregation 一套写完
Possible exam prompt:
Store ZIP-code population records. Find Tennessee cities with population above a threshold, update a record, create an index, and compute total population by state.
写题顺序:
- 选数据库。
- 插入数据,注意
_id类型。 - filter 选文档,projection 选字段。
$set修改。- 建与查询匹配的索引。
$match → $group → $sort统计。
javascript
use cs4288
// 1. ZIP 是标识字符串,保留可能存在的前导 0。
db.zips.insertMany([
{
_id: '37201',
city: 'NASHVILLE',
state: 'TN',
pop: 1579,
},
{
_id: '38103',
city: 'MEMPHIS',
state: 'TN',
pop: 4144,
},
{
_id: '90001',
city: 'LOS ANGELES',
state: 'CA',
pop: 51841,
},
]);
// 2. TN 且人口 >= 1000;只返回这几个字段。
// $gte 是本例补充的“包含下界”比较操作符。
db.zips.find(
{ state: 'TN', pop: { $gte: 1000 } },
{ _id: 1, city: 1, pop: 1 }
).sort({ pop: -1, _id: 1 });
// 3. 局部更新:city / state 等未指定字段保留。
db.zips.updateOne(
{ _id: '37201' },
{ $set: { pop: 2000 } }
);
// 4. 按 state 定位,再按 city 检索的复合索引。
db.zips.createIndex({ state: 1, city: 1 });
// 5. 查看扫描代价,而不只看“有没有索引”。
db.zips.find({
state: 'TN',
city: 'NASHVILLE',
}).explain('executionStats');
// 6. 按州统计。
// 此时 TN 是 2000 + 4144 = 6144,不再是更新前的 5723。
db.zips.aggregate([
{
$group: {
_id: '$state',
totalPop: { $sum: '$pop' },
zipCount: { $sum: 1 },
},
},
{ $sort: { totalPop: -1, _id: 1 } },
{
$project: {
_id: 0,
state: '$_id',
totalPop: 1,
zipCount: 1,
},
},
]);题目常见变体:
- “只统计 TN”:在 group 前加
$match。 - “每个州人口前 N 名”:先明确是在州总量上取前 N,还是州内城市前 N,不能直接套一个全局 limit。
- “按城市汇总 ZIP”:group key 可为
{ state: '$state', city: '$city' },避免不同州同名城市被误合并。 - “只返回州和总人口”:project 去
_id并重命名。 - “删除一个字段”:
$unset,不要 deleteOne。 - “清空匹配数据”:deleteMany。
- “整个文档替换”:replaceOne,不是 updateOne 普通对象。
3.7 【代码理解题】Pipeline 顺序
javascript
db.zips.aggregate([
{ $sort: { pop: -1, _id: 1 } },
{ $skip: 10 },
{ $limit: 5 },
]);含义:排序后跳过前 10 条,取接下来的 5 条。
javascript
db.zips.aggregate([
{ $limit: 5 },
{ $skip: 10 },
]);含义:先最多保留 5 条,再跳过 10 条,结果为空。
不要把 aggregation 的 stage 顺序,与普通 find cursor 对 skip / limit 的处理规则混为一谈。
3.8 【代码大题扩展】Express + Mongoose 完整微型服务
课件没有 Mongoose / Express 服务。此例沿用课件 ZIP 模型,帮助把查询、更新与聚合接到 HTTP。
使用字符串 ZIP 作为_id,因此这里 不需要将路径参数转 ObjectId。代码已通过 Node 语法检查;未连接真实 MongoDB 做端到端运行。
接口:
| Method | 路径 | 功能 |
|---|---|---|
| GET | /api/zips?state=TN&minPop=1000&limit=20 | 条件查询 |
| POST | /api/zips | 新增 ZIP 文档 |
| PATCH | /api/zips/:zip | 更新人口 |
| GET | /api/stats/states?state=TN | 按州聚合 |
准备:
bash
npm init -y
npm install express mongoose
node server.cjs需要 MongoDB 服务已经运行,默认连接本机 27017。
javascript
const http = require('node:http');
const express = require('express');
const mongoose = require('mongoose');
const app = express();
// 1. 公共 middleware:注册,不是开端口。
app.use((req, res, next) => {
console.log(req.method, req.originalUrl);
next();
});
// 2. JSON parser 必须在读取 req.body 的 route 前。
app.use(express.json({ limit: '100kb' }));
// 3. Schema 是应用侧规则。
// _id 明确为 String,不使用默认 ObjectId。
const schema = new mongoose.Schema(
{
_id: {
type: String,
required: true,
match: /^\d{5}$/,
},
city: {
type: String,
required: true,
trim: true,
uppercase: true,
maxlength: 100,
},
state: {
type: String,
required: true,
uppercase: true,
match: /^[A-Z]{2}$/,
},
pop: {
type: Number,
required: true,
min: 0,
validate: Number.isInteger,
},
},
{ timestamps: true }
);
// 声明索引,不代表每次请求都重新建索引。
schema.index({ state: 1, city: 1 });
// 第三个参数明确指定 collection 名 zips。
const Zip = mongoose.model('Zip', schema, 'zips');
// 兼容 Express 4 / 5 的 async 错误传递。
const wrap = fn => (req, res, next) => {
return Promise.resolve()
.then(() => fn(req, res, next))
.catch(next);
};
function badRequest(message) {
const err = new Error(message);
err.status = 400;
throw err;
}
// 只构造自己允许的 filter,不直接 Zip.find(req.query)。
function stateFilter(value) {
if (value === undefined) return {};
if (
typeof value !== 'string' ||
!/^[a-zA-Z]{2}$/.test(value)
) {
badRequest('state 必须是两个英文字母');
}
return { state: value.toUpperCase() };
}
// 4. GET:query → 校验/转换 → filter → find → JSON。
app.get('/api/zips', wrap(async (req, res) => {
const filter = stateFilter(req.query.state);
if (req.query.minPop !== undefined) {
if (
typeof req.query.minPop !== 'string' ||
!/^\d+$/.test(req.query.minPop)
) {
badRequest('minPop 必须是非负整数');
}
const minPop = Number(req.query.minPop);
if (!Number.isSafeInteger(minPop)) {
badRequest('minPop 过大');
}
filter.pop = { $gte: minPop };
}
let limit = 20;
if (req.query.limit !== undefined) {
if (
typeof req.query.limit !== 'string' ||
!/^\d+$/.test(req.query.limit)
) {
badRequest('limit 必须是正整数');
}
const value = Number(req.query.limit);
if (!Number.isSafeInteger(value) || value < 1) {
badRequest('limit 必须是正整数');
}
limit = Math.min(value, 100);
}
const items = await Zip.find(filter)
.select('_id city state pop')
.sort({ pop: -1, _id: 1 })
.limit(limit)
.lean() // 只读输出,返回普通对象。
.exec(); // 执行 Query,得到 Promise。
res.json({ items });
}));
// 5. POST:body → 白名单字段 → create → 201。
app.post('/api/zips', wrap(async (req, res) => {
const body = req.body;
if (
!body ||
typeof body.zip !== 'string' ||
!/^\d{5}$/.test(body.zip) ||
typeof body.city !== 'string' ||
!body.city.trim() ||
body.city.trim().length > 100 ||
typeof body.state !== 'string' ||
!/^[a-zA-Z]{2}$/.test(body.state) ||
!Number.isSafeInteger(body.pop) ||
body.pop < 0
) {
badRequest('zip/city/state/pop 格式不正确');
}
const item = await Zip.create({
_id: body.zip,
city: body.city,
state: body.state,
pop: body.pop,
});
res.status(201).json(item);
}));
// 6. PATCH:params 找文档,body 提供新值。
app.patch('/api/zips/:zip', wrap(async (req, res) => {
if (!/^\d{5}$/.test(req.params.zip)) {
badRequest('zip 格式不正确');
}
const pop = req.body?.pop;
if (!Number.isSafeInteger(pop) || pop < 0) {
badRequest('pop 必须是非负整数');
}
const item = await Zip.findByIdAndUpdate(
req.params.zip,
{ $set: { pop } },
{
returnDocument: 'after', // 返回更新后的文档。
runValidators: true, // 开启更新校验。
}
).exec();
if (!item) {
return res.status(404).json({ error: 'Zip not found' });
}
res.json(item);
}));
// 7. 聚合:不要把所有文档拉回 Node 再自己 reduce。
app.get('/api/stats/states', wrap(async (req, res) => {
const filter = stateFilter(req.query.state);
const items = await Zip.aggregate([
{ $match: filter },
{
$group: {
_id: '$state',
totalPop: { $sum: '$pop' },
zipCount: { $sum: 1 },
},
},
{ $sort: { totalPop: -1, _id: 1 } },
{
$project: {
_id: 0,
state: '$_id',
totalPop: 1,
zipCount: 1,
},
},
]).exec();
// 聚合结果本来就是普通结果对象,不需要再 lean。
res.json({ items });
}));
// 8. 未匹配接口。
app.use((req, res) => {
res.status(404).json({ error: 'Route not found' });
});
// 9. Error middleware:四个参数,放在 routes 后面。
app.use((err, req, res, next) => {
if (res.headersSent) return next(err);
if (err.code === 11000) {
return res.status(409).json({
error: 'ZIP already exists',
});
}
if (err.type === 'entity.parse.failed') {
return res.status(400).json({ error: 'Invalid JSON' });
}
if (err.type === 'entity.too.large') {
return res.status(413).json({ error: 'Body too large' });
}
if (
err.status === 400 ||
err.name === 'ValidationError' ||
err.name === 'CastError'
) {
return res.status(400).json({ error: err.message });
}
console.error(err);
res.status(500).json({ error: 'Internal server error' });
});
// 10. 启动时建立一次连接,再开放 HTTP。
async function main() {
await mongoose.connect(
process.env.MONGO_URI ||
'mongodb://127.0.0.1:27017/cs4288',
{ serverSelectionTimeoutMS: 5000 }
);
// 本示例在默认 autoIndex 配置下等待模型初始化/索引准备。
// 真实部署可采用独立索引管理流程。
await Zip.init();
const server = http.createServer(app);
const port = Number(process.env.PORT || 8080);
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(port, '127.0.0.1', resolve);
});
console.log(`HTTP listening on http://127.0.0.1:${port}`);
}
main().catch(async err => {
console.error(err);
await mongoose.disconnect();
process.exitCode = 1;
});请求例子:
bash
curl -X POST http://127.0.0.1:8080/api/zips \
-H 'Content-Type: application/json' \
-d '{"zip":"37201","city":"Nashville","state":"TN","pop":1579}'
curl 'http://127.0.0.1:8080/api/zips?state=TN&minPop=1000&limit=10'
curl -X PATCH http://127.0.0.1:8080/api/zips/37201 \
-H 'Content-Type: application/json' \
-d '{"pop":2000}'
curl 'http://127.0.0.1:8080/api/stats/states?state=TN'这段代码的得分点:
req.query是查询筛选,req.params是路径标识,req.body是提交内容。- 先解析 body,再读 body。
- 字符串 ZIP 保留前导零,不乱转 Number / ObjectId。
- 字段白名单,避免直接把整个用户对象交给数据库。
.find()与.aggregate()都要执行并等待结果。$set局部更新,runValidators更新校验。- aggregation 在数据库执行。
- DB ready 后才监听。
- 错误交给统一 middleware。
3.9 Mongoose 高频 API(扩展速查)
mongoose.connect(uri)— 异步建立连接,通常启动时调用并复用。new mongoose.Schema(fields, options)— 定义应用侧结构,不插入文档。schema.index({ state: 1, city: 1 })— 声明索引;实际建立受模型初始化与配置影响。mongoose.model('Zip', schema, 'zips')— Model 名 Zip,集合明确为 zips。new Zip(data)— 创建内存 Document,尚未保存。await doc.save()— 校验并持久化 Document。await Zip.create(data)— 创建并保存,返回 Document。await Zip.find(filter).exec()— 返回 Document 数组,没匹配为[]。await Zip.findOne(filter).exec()— 返回一条或 null。await Zip.findById(id).exec()— 按 Schema 的_id类型查询;本例是 String。.select('city state pop')— 查询 projection;_id通常仍保留。.sort({ pop: -1 })— 排序。.limit(20)— 限制结果数。.lean()— 普通查询返回 POJO,不带 Document 的 save / 变更跟踪。.exec()— 执行 Query / Aggregate 并返回 Promise。await Zip.updateOne(filter, { $set: patch }, { runValidators: true })— 返回写入结果,不直接返回更新后文档。await Zip.findByIdAndUpdate(id, update, { returnDocument: 'after', runValidators: true })— 返回更新后文档或 null。await Zip.deleteOne(filter)— 返回删除结果,检查 deletedCount。await Zip.aggregate(pipeline).exec()— 返回聚合结果数组;不是普通 find Query 的 Document 包装。await mongoose.disconnect()— 关闭连接。
容易考的 Mongoose 边界:
unique: true是索引相关设置,不是普通 validator。- Schema 不自动限制绕过 Mongoose 的原生写入。
- 查询结果不存在与 ID 格式错误不同。
- update 校验通常需要
runValidators: true,且不等同完整 save 校验。 - Mongoose Query 可 await,但不是可以重复执行的普通 Promise。
- 聚合中的字段类型转换不要无条件依赖普通查询的自动 casting。
参考:Mongoose — Queries、Schemas、Validation、Lean。
3.10 原生 MongoDB Driver:同一套操作怎么写
javascript
const { MongoClient } = require('mongodb');
async function main() {
const client = new MongoClient(
'mongodb://127.0.0.1:27017'
);
await client.connect();
try {
const zips = client.db('cs4288').collection('zips');
// 查询返回 cursor,用 toArray 异步读成数组。
const items = await zips
.find({ state: 'TN' })
.project({ city: 1, state: 1, pop: 1 })
.sort({ pop: -1, _id: 1 })
.limit(20)
.toArray();
// 原生 updateOne 返回 UpdateResult。
const result = await zips.updateOne(
{ _id: '37201' },
{ $set: { pop: 2000 } }
);
const stats = await zips.aggregate([
{ $match: { state: 'TN' } },
{
$group: {
_id: '$state',
totalPop: { $sum: '$pop' },
},
},
]).toArray();
console.log(items, result.modifiedCount, stats);
} finally {
// 这是一次性脚本,所以结束时关闭。
// HTTP 服务中应复用 client,不要每个请求都 connect/close。
await client.close();
}
}
main().catch(console.error);| 操作 | Shell / Native driver | Mongoose |
|---|---|---|
| 查多条中间对象 | cursor | Query |
| 获取结果数组 | driver .toArray() | await Model.find().exec() |
| 插入一条 | insertOne → result / insertedId | create → Document |
| 聚合 | aggregate cursor | Aggregate,exec 后结果数组 |
| 保存实例 | driver 没有 Mongoose doc.save 机制 | doc.save |
| 类型规则 | 数据库配置与应用逻辑 | Schema casting / validation 等 |
3.11 Express 常用 API:干活时的思维导引
express()— 建 app,还没监听。app.use(fn)— 挂公共处理步骤。app.use(express.json())— 让 JSON body 进入 req.body。app.use('/api', router)— 把一组路由挂到 /api 前缀。app.get('/api/zips', handler)— 注册查询接口。app.post('/api/zips', handler)— 注册新增接口,真正新增由 handler 的数据库代码完成。app.patch('/api/zips/:zip', handler)— 注册更新接口。app.delete('/api/zips/:zip', handler)— 注册删除接口,不会自动删库。req.query— 问号后筛选条件。req.params.zip— 路径中 :zip 的值。req.body— 请求正文,依赖 parser。res.status(201)— 设状态码,还没单独完成响应。res.json(data)— 发 JSON 并结束响应。return res.status(404).json(...)— 发错误响应,并退出当前 JS handler。next()— 交下一层。next(err)— 交错误处理。app.use((err, req, res, next) => {...})— 统一处理错误,四个参数。http.createServer(app)— 把 app 接成 HTTP server。server.listen(port)/app.listen(port)— 开端口监听,不是 app.use。
4. True / False Traps(判断题陷阱)
Data Model / BSON / IDs
- True —
Documents in one collection can have different structures.— 灵活结构。(p.8) - False —
Schema-free means schema design is unnecessary.— 仍需按访问方式设计。(p.32–40) - False —
MongoDB cannot enforce any schema validation.— 可配置服务器 validation。(补充) - False —
A collection is limited to 16 MiB.— 限制针对单个 BSON 文档。(p.8) - False —
Embedded documents do not count toward the parent document size.— 都计入。 - False —
BSON is always smaller than JSON.— 二进制编码不保证体积更小。(p.10;限定) - False —
BSON Date and BSON Timestamp are the same type.— 类型编号也不同。(p.12) - True —
The $type operator can query by BSON type.— 课件明确。(p.12) - False —
The slide's MinKey value 255 should always be used as $type: 255.— 查询使用 -1 / minKey。(p.12;修正) - False —
Every _id must be an ObjectId.— 允许其他合适类型。(p.13) - False —
_id is globally unique across all collections by definition.— 常规唯一范围是集合。 - False —
Sorting by ObjectId guarantees exact chronological creation order.— 大致接近,不是严格保证。(p.13) - False —
A string ID and an ObjectId with the same printed text are the same BSON value.— 类型不同。 - False —
A reference automatically enforces a foreign-key constraint.— 普通引用值不会自动建立约束。
CRUD / Atomicity
- False —
use newdb immediately persists a new populated database.— 切换上下文不等于持久创建。(p.18) - False —
find returns an array containing every matching document.— 返回 cursor。(p.21) - False —
The shell displaying 20 results means find matched at most 20 documents.— 显示行为不等于查询上限。(p.21) - False —
findOne always returns the newest matching document.— 需明确排序等条件。 - True —
Multiple field conditions in a filter normally form an implicit AND.— p.22。 - False —
$or takes a plain sequence of field-value pairs without condition objects.— 数组元素应是条件对象。(p.23;修正) - False —
Projection changes which documents match the filter.— projection 决定返回字段。(p.24) - False —
Projection removes excluded fields from stored documents.— 不修改数据库。(p.24) - False —
An inclusion projection always removes _id automatically.— 默认通常保留。(补充) - False —
$exists: true excludes fields whose value is null.— 有字段且为 null 仍匹配。 - False —
$unset sets a field to null.— 是移除字段。(p.26) - False —
updateOne with multi:true updates all matching documents.— 应使用 updateMany。(p.25;修正) - False —
Modern updateOne accepts a plain replacement document to replace all fields.— 应使用 replaceOne。(p.26;修正) - False —
upsert is enabled by default.— 默认不自动插入。(p.25) - False —
deleteOne requires true as its second argument to delete one document.— 课件混用旧语法。(p.27) - False —
deleteMany({}) drops the collection and all its indexes.— 删除文档不等于 drop。 - True —
A single-document update is atomic even when it modifies multiple fields.— p.28。 - False —
updateMany is automatically atomic across all matched documents.— 默认不作整体事务。 - False —
A separate read followed by a write is automatically one atomic operation.— 两步存在并发窗口。 - False —
MongoDB never supports multi-document transactions.— 现代版本支持。(补充) - False —
$isolated is the recommended modern transaction API.— 旧功能,不照抄。(p.28)
Modeling / Indexes
- False —
One-to-many relationships must always use embedding.— 课件展示 embedding 与 linking。(p.37–39) - True —
Embedding can improve locality for data accessed together.— p.39、46。 - False —
Embedding always avoids duplication and update complexity.— 共享实体副本可能需要多处修改。 - False —
The checkout document shape alone guarantees a book cannot appear under two students.— 需额外一致性设计。(p.43–45) - False —
A dotted field path always creates a multikey index.— 要看是否涉及数组。(p.53) - False —
Compound and multikey mean the same thing.— 多字段与数组索引不同。 - False —
A regular index on a coordinate array is automatically a geospatial index.— 普通 loc 数组索引不是地理索引。 - False —
Creating an index guarantees every query will use it.— 优化器根据查询选择。 - False —
More indexes always make writes faster.— 写入还需维护索引。 - False —
A compound index's field order does not matter.— 顺序影响能力。(p.52) - False —
hint creates an index if it does not exist.— 指定索引,不创建。(p.50) - False —
hint is a substitute for an explicit sort requirement.— 不作为业务排序契约。 - False —
dropIndex removes the indexed field from documents.— 只删索引。 - True —
An index can reduce scanned documents while returning the same logical results.— p.60–61。 - False —
Using an index means MongoDB never reads collection documents.— 可能仍需 FETCH。
Aggregation / Map-Reduce
- True —
Pipeline stages consume the output of earlier stages.— 顺序执行。(p.63) - False —
Each pipeline stage must output exactly one document for every input document.— 可过滤、分组等。(p.70) - False —
Pipeline stages can always be reordered without changing results.— skip / limit 等明显不同。 - False —
$group automatically sorts its output.— 要 sort。 - False —
_id: 'TN' and _id: '$state' define the same grouping in every pipeline.— 常量与字段引用不同。 - True —
$sum: '$pop' adds population values; $sum: 1 counts input documents.— 分清合计与计数。 - False —
All modern aggregation results combined must fit inside 16 MiB.— 主要是单个返回文档限制。(p.66、71;修正) - False —
Aggregation always modifies the source collection.— 普通统计不改;写入 stage 是例外。 - False —
Map must emit exactly one key-value pair for each input document.— 可零个或多个。(p.66;修正) - False —
Map-Reduce's finalize phase is mandatory.— 可选。(p.66) - False —
Array.sum is a standard JavaScript method in Node.js.— 课件旧环境 helper。(p.67) - False —
Map-Reduce with out only reads data and cannot write a collection.— out 写结果集合。 - False —
The historical group command and the $group pipeline stage are the same API.— 不同。 - False —
distinct returns complete matching documents.— 返回字段的不同值。(p.69、73)
Replication / Sharding
- True —
Secondaries replicate asynchronously.— 可能存在 lag。(p.76) - False —
All application writes can be sent directly to any secondary.— 普通写入由 primary 接收。 - False —
An arbiter stores a full replica of the data.— 投票但不存数据副本。 - False —
Every secondary is necessarily eligible to become primary.— 配置可能限制资格。 - False —
A delayed secondary can serve as primary while retaining its delayed configuration.— priority 0。(p.76) - False —
Automatic failover guarantees no interruption to writes.— 选举期间可中断。 - False —
Replica sets with an even total number of members are always invalid.— 推荐投票配置不等于硬性总数规则。 - False —
Replication is equivalent to a complete backup strategy.— 误操作可同步传播。 - True —
Sharding distributes data; replication duplicates data.— 核心区分。 - False —
Replication and sharding cannot be used together.— shard 可是 replica set。(p.74、79) - False —
mongos is the MongoDB interactive shell.— 是分片 query router。 - False —
A high-cardinality shard key guarantees no hotspots.— 还受频率和单调性影响。 - False —
A monotonically increasing range-based shard key always distributes new writes evenly.— 可能集中末端。 - False —
The CP label guarantees every secondary read is immediately up to date.— 不能跨配置绝对化。(p.3、76)
5. Exam Quick Reference(考前速查)
Definitions
- MongoDB: document database;BSON;collection 内结构可不同。(p.8)
- 16 MiB: 单个 BSON 文档,不是集合总大小。
- Schema-free: 灵活结构,不是免建模 / 免校验。
- BSON: binary serialization,非“压缩 JSON”。
_id: 普通集合内唯一、不可变;不必须 ObjectId。- ObjectId: 12 bytes / 常见 24 hex;近似时间顺序,非严格先后。
mongod: DB server;mongosh / mongo: shell;mongos: shard router。
CRUD
- find → cursor;findOne → doc / null。
- AND:
{ a: 1, b: 2 }。 - OR:
{ $or: [{ a: 1 }, { b: 2 }] }。 - IN:
{ a: { $in: [1, 2] } }。 - Projection: 第二参数;1 包含,0 排除;
_id默认保留。 - Exists: 存在包括 null;缺失不同于显式 null。
$set: 改字段;$unset: 移除字段。- updateOne: 一条;updateMany: 多条。
- replaceOne: 替换非
_id内容。 - upsert: 无匹配时插入,默认关闭。
- deleteMany({}): 清文档,不是 drop。
- Atomic: 单文档写原子;多文档默认非整体事务。
Indexes
- 1 / -1: 升序 / 降序,不是 projection。
- Single: 一个字段;compound: 多字段且顺序重要;multikey: 数组。
- ensureIndex: 旧;createIndex: 现代写法。
- hint: 指定已有索引,不创建、不保证更快、不代替 sort。
- explain: 看扫描与计划,不只看执行时间。
- 截图: Nashville 返回 19 条;无索引扫描约 29467,有相关索引约 19。(p.60–61)
Aggregation
- Pipeline: match → group → sort → project。
'$pop': 字段;'pop': 字符串。_id: '$state': 按州;_id: 'TN': 常量组。$sum: '$pop': 人口合计;$sum: 1: 文档计数。- p.64: TN 小样本
1579 + 4144 = 5723。 - p.67: Nashville Map-Reduce 小样本
1579 + 612 = 2191。 - Map-Reduce: map emit → reduce → optional finalize;旧 API,已弃用。
- Array.sum: 旧 helper,非 JS 标准。
- distinct: 去重值;旧 group ≠
$group。 - 现代结果大小: 每个结果文档 16 MiB,不是所有结果总和。
Replication & Sharding
- Primary: 写入;secondary: 异步复制;arbiter: 投票不存数据。
- Delayed: 延迟数据、不可当 primary。
- Failover: heartbeats + majority election,可能有写入空窗。
- Replication: 冗余 / 可用性;sharding: 水平分布。
- Shard key: cardinality + frequency + monotonicity + query pattern。
- Hotspot: 高基数也可能发生。
- 可组合: 每个 shard 用 replica set。
代码题优先级
- CRUD + filter + projection + update / replace 辨别。(p.19–28)
- Index / hint / explain 分析。(p.50–61)
$match + $group + $sum + $sort统计。(p.64–65)- Embedding / referencing 数据模型设计。(p.35–45)
- 读懂旧 Map-Reduce,不把它当当前首选服务实现。(p.67、72)
- Express 扩展口诀:use 挂步骤,get/post 注册接口,listen 开端口;DB connect 不等于 HTTP listen。
Lecture 22 — MongoDB with Node.js
本章共 13 页,页码包含标题页。
【课件修正】:代码笔误、旧版本配置或不准确概括。【补充】:理解代码行为所需知识。【代码题扩展】:根据课件组织的可复用例题。
1. Core Concepts(核心概念)
Application Data Analysis(数据存储选型)
Choose persistence according to the application's data and access requirements.
先分析保存什么、如何读取、关系和生命周期,再选择存储方案。(p.3)
| Storage type | 课件关键词 | 考试识别 |
|---|---|---|
| In-memory key–value | High-performance、transient、simple structure | 高速、临时、简单键值 |
| SQL database | Robust、highly structured、transactional | 强结构、事务、关系模型 |
| Document-oriented database | Scalable、flexible schema、loose relationships | 灵活文档结构与扩展 |
| Graph database | Relationship-oriented、algorithmic necessity | 关系遍历、图算法 |
| Search engine | High query throughput、indices、search facilities | 搜索与检索能力 |
【课件限定】These are typical strengths, not exclusive capabilities.
- 不能推断文档数据库不支持事务。
- 不能推断内存键值数据库永远不能持久化。
- 不能推断 SQL 数据库不能扩展。
- 一个应用可以组合多种存储,不要求所有数据进入同一种数据库。
Entities & Relationships(实体与关系)
Identify each entity's structure and its relationships with other entities.(p.4)
课件图中的实体包括:
- User
- Tx — Transaction
- Address
- Block
- Wallet
- 尚未确定的其他实体
考试重点:
- 明确每种实体保存哪些属性。
- 明确实体之间如何关联。
- 再决定 embedding、reference、索引与查询方式。
- 图中箭头不是完整的基数定义,不能仅凭它推断某关系一定是一对一或一对多。
Mongoose — ODM(对象文档映射)
Mongoose provides schemas, models, documents, validation, and middleware for MongoDB applications.(p.5–11)
- MongoDB:数据库。
- MongoDB Node driver:与数据库通信的驱动。
- Mongoose:在 driver 之上的 ODM。
- Express:HTTP 路由和 middleware。
- Joi:输入验证库。
Mongoose is not the MongoDB server.
- Schema、部分校验和 hooks 在 Node.js 应用进程中执行。
- 使用 Mongoose 不等于数据库只能通过 Mongoose 访问。
- 绕过 Mongoose 的写入,不会自动经过应用里的 Mongoose hooks。
Schema vs. Model vs. Document(最容易混淆的三层)
课件 p.5:
javascript
const Cat = mongoose.model('Cat', { name: String });
const kitty = new Cat({ name: 'Tiger' });
await kitty.save();| 名称 | 是什么 | 是否已经写入数据库 |
|---|---|---|
| Schema | 文档结构、类型、规则、hooks 等定义 | 否 |
| Model | 根据 Schema 编译的操作入口 / 构造函数 | 否 |
| Document | new Model(...) 得到的文档实例 | 尚未必 |
save() | 校验并持久化 Document | 成功后才完成相应写入 |
Execution order(p.5):
- 加载 mongoose。
- 发起数据库连接。
- 定义 / 获取 Cat Model。
- 创建内存 Document。
- 等待 save。
- save 成功后输出
meow。
Traps:
new Cat(...)不等于插入。console.log('meow')不会因 save 仍在等待而提前执行。- save 失败时,若没有 catch,正常流程不会继续到该日志。
await需要合法的 async 上下文或支持顶层 await 的 ESM;课件的 CommonJS 片段不能不加包装直接照抄。
Connections(数据库连接)
mongoose.connect() is asynchronous.(p.5–6)
课件 URI:
mongodb://localhost/test— 本机 test 数据库,未明确端口时通常使用默认 MongoDB 端口。mongodb://localhost:32768/foobar— 本机 32768 端口,数据库 foobar。- URI 的数据库名不是 collection 名。
- 数据库连接池不是 HTTP 端口监听。
- 一个连接池不等于只允许处理一个 HTTP 请求。
- 应用通常在启动时建立连接并复用,不在每个 route 中重新 connect / disconnect。
【补充】Mongoose may buffer operations while connecting.
- p.5 没有 await connect,但后续模型操作可能被缓冲等待连接。
- 这不表示连接是同步完成。
- 完整服务通常明确
await mongoose.connect(...),成功后再开始监听 HTTP。
【课件修正】p.6 的复杂 options 属于旧版本格式。
| 旧课件配置 | 原意 | 现代理解 |
|---|---|---|
db.native_parser: true | 旧 BSON parser 选项 | 不照抄到当前版本 |
server.poolSize: 5 | 连接池大小 | 常用顶层 maxPoolSize: 5 |
replset.rs_name | replica set 名称 | 常用 replicaSet |
user / pass | 数据库认证信息 | 与应用用户登录是两回事 |
【补充】 本机示例使用 127.0.0.1 可避免部分 localhost → IPv6 地址解析带来的连接差异。
Application Schema vs. Database Constraints(校验执行位置)
课件 p.7–8 的核心:
Mongoose schemas are enforced by the Node.js application using Mongoose.
但不能扩大为:
- MongoDB 服务器永远不能做 validation。
- 唯一性只能由 Web server 检查。
- MongoDB 没有数据库端查询或 join-like 能力。
【课件限定】The diagram is a simplified division of responsibilities.
- Mongoose validation:应用侧。
- Unique index:数据库侧约束。
- MongoDB 可以配置 collection validation。
- Mongoose populate 与数据库
$lookup不是同一个机制。
Schema Types(Schema 类型)
课件列出:(p.8)
| Type | 含义 / 易错点 |
|---|---|
String | 字符串 |
Number | JS 数值对应的 Schema 类型,不等于自动要求整数 |
Date | 日期 |
Buffer | 二进制 |
Boolean | 布尔 |
Mixed | 灵活混合内容,弱化固定结构检查 |
ObjectId | 引用 / 标识常用类型 |
Array | 数组 |
【补充】Casting is different from validation.
- Mongoose 可能先进行类型转换。
- 声明 Number 不等于请求中的原值必须已经是 JS Number。
- 字符串
"123"可能被转为数值。 - 转换失败可能产生 CastError。
- 需要严格 API 输入类型时,可在进入 Mongoose 前用 Joi 检查。
ObjectId distinction:
Schema.Types.ObjectId:定义字段类型。mongoose.Types.ObjectId:构造 / 使用实际 ObjectId 值。- p.9 示例使用 Number 类型主键,说明 reference 不必须是 ObjectId。
Required vs. Unique(必填与唯一)
课件 p.8:
javascript
username: {
type: String,
required: true,
index: { unique: true },
}required: true:字段必须满足 required 校验。index: { unique: true }:声明唯一索引。- Unique is not a normal Mongoose validator.
- 真正防止并发重复写入的是数据库唯一索引。
- 先
findOne()检查不存在,再 insert,不足以替代唯一索引。 - 索引尚未建立时,不能只凭 Schema 声明假定约束已生效。
- 重复键通常表现为数据库 duplicate-key 错误,例如 code 11000,而不是普通 ValidationError。
References & Populate(引用与关联加载)
课件 p.9:
- Person 的
_id为 Number。 - Story 的
_creator为 Number,ref: 'Person'。 - fans 是 Number reference 数组。
.populate('_creator')获取创建者文档。
ref identifies the Mongoose model used for population.
'Person'是注册的 Model 名称,不是任意字段名。- 引用字段类型需要与被引用
_id类型相匹配。 - 普通查询拿到的是 reference 值。
- populate 后,返回对象对应路径可被替换为关联文档。
- populate 不会把数据库里原本的 reference 自动改成嵌入文档。
- 不会自动创建被引用文档。
- 不自动建立数据库外键约束或级联删除。
- 通常涉及额外关联查询,不等于自动变成一个数据库 SQL JOIN。
Missing-data behavior(补充):
- Story 本身不存在:findOne 返回 null。
- Story 存在但单个关联不存在:populated 路径通常为 null。
- 关联数组没有找到文档:通常为空数组。
- 因此直接
story._creator.name可能因 null 报错。
【课件修正】p.9 不能直接运行。
wait Story应为await Story。- 上面定义的是 Schema,但查询要对 Model 调用。
- 需要
mongoose.model('Person', personSchema)等注册。 Schema也需要从 mongoose 取得。findOne({ title: ... })是按实际字符串匹配,不会自动“纠正标题拼写”。
Mongoose Middleware — Pre / Post Hooks(操作钩子)
Mongoose middleware runs around specified model or document operations.(p.10–11)
课件结构:
pre → operation → post
课件列举操作:
- init
- validate
- save
- remove
课件列举执行方式:
- serial
- parallel
【版本限定】 这是概括和部分历史 API,不代表当前所有 hook 都支持完全相同的 serial / parallel 写法。
重要边界:
- hooks 应在编译 Model 前定义。
- document save hook 中普通函数的
this通常是当前 Document。 - 箭头函数不会获得同样的动态 this。
- query middleware 中 this 可能是 Query,而不是 Document。
save()hooks 不会自动覆盖所有updateOne()/findOneAndUpdate()操作。inithooks 是同步例外,不能把全部 hook 都当成异步。- 旧
remove相关 hook 写法需要按版本检查,当前删除接口通常使用 deleteOne 等。
Validation vs. Sanitization(验证与清理)
课件 p.11:
- 自定义 phone validator。
pre('save')中对姓名字符串执行 replace。
Validation checks whether data is acceptable.
校验判断是否接受输入。
Sanitization / normalization changes the data.
清理 / 规范化会修改输入或待保存字段。
课件姓名处理:
javascript
this.first_name = this.first_name.replace(/<(?:.|\n)*?>/gm, '');含义:
- 用正则删除形似标签的片段。
- replace 返回新字符串。
- 赋值回 Document 才改变待保存字段。
- 字段不存在或不是字符串时,直接
.replace()可能失败。
【课件限定】This regex is not a complete HTML sanitizer.
- 不能据此认为所有 XSS / HTML 输入问题都已解决。
- 如果只是显示普通文本,还需对应输出上下文的正确处理。
【补充】Validation normally runs before ordinary pre-save hooks.
- 若希望校验基于规范化后的值,可考虑
pre('validate')或 Schema setter。 - 不要默认“任意 pre-save 修改都会再完整执行一轮 validation”。
Phone Regex(课件中的可直接出题笔误)
课件写:
javascript
/d{3}-d{3}-d{4}/【课件修正】It matches literal d characters, not digits.
d:字母 d。\d:数字字符类。- 缺少
^/$时可匹配字符串中的一段,不要求整个输入完全符合。
按课件意图修正:
javascript
/^\d{3}-\d{3}-\d{4}$/123-456-7890:通过。ddd-ddd-dddd:不通过修正版,但可匹配课件原正则。prefix123-456-7890suffix:不通过带锚点版本。- p.11 的 phone 没写 required,不能自动推断它一定必填。
Joi — API Input Validation(API 层校验)
Joi can validate input before database operations are attempted.(p.12)
课件 Schema:
| 字段 | 规则 |
|---|---|
| username | string、lowercase、alphanum、3–32 字符、required |
| primary_email | string、lowercase、email、required |
| first_name | string,可为空字符串 |
| last_name | string,可为空字符串 |
| city | string,缺失时默认 '' |
| password | string,至少 5 字符、required |
Joi behavior traps(必要补充):
- 默认
convert: true,lowercase 等可返回转换后的数据。 - 应使用
validateAsync()的返回值,不能校验后仍无条件使用原 req.body。 .required()不等于“只是提示文字”,会影响 undefined 的接受。.allow('')允许空字符串,不等于自动默认成空字符串,也不等于必填。.default('')在缺失等默认触发情形提供值;不表示显式空字符串一定被原规则接受。.alphanum()通常只允许英文字母和数字,不包括下划线和连字符。.email()校验格式,不验证邮箱真实存在。.min(5)只是一条长度规则,不表示密码已被 hash 或满足完整强度要求。- 未配置 required 的字段通常可缺失。
- 定义了 keys 的普通 Joi object 默认通常不接受额外未知字段,除非调整 options。
validateAsync()成功 resolve 验证后的值,失败 reject。.validate()的同步形式通常返回{ value, error },与 async 返回形态不同。
参考:Joi — API。
2. Comparisons & Distinctions(易混淆概念对比)
| 概念 | 负责什么 | 不负责什么 |
|---|---|---|
| Express | HTTP 路由、middleware、响应 | 自动执行数据库业务 |
| MongoDB driver | 与数据库通信 | 提供全部 Mongoose Schema 抽象 |
| Mongoose | Model、Document、校验、hooks、populate | 替代 MongoDB server |
| Joi | 验证 / 转换 API 输入 | 数据库唯一性最终保证 |
| Unique index | 数据库中防止重复键 | 普通输入格式校验 |
| Password hash | 密码验证依据 | session ID |
| Session | 跨请求关联用户会话 | 自动验证任意传来的密码 |
| 对比 | A | B |
|---|---|---|
| Schema vs. Model | 结构与规则定义 | 编译后的操作入口 |
| Model vs. Document | 一类文档的构造 / 查询接口 | 一条实例 |
new Model vs. save | 只创建内存实例 | 持久化 |
| Embedded vs. populated | 子内容实际存在父文档 | 关联加载返回引用目标 |
| Required vs. unique | 字段校验 | 唯一索引约束 |
| Joi vs. Mongoose validation | API 边界 | 文档 / 模型操作层 |
| Validation vs. sanitization | 判断接受与否 | 修改 / 规范化值 |
| save hook vs. query hook | 操作 Document | 操作 Query,this 不同 |
3. APIs & Configurations(API 与配置速查)
Connection & Model(p.5–8)
const mongoose = require('mongoose')— 加载 ODM,需安装 mongoose 包。const { Schema } = mongoose— 取得 Schema 构造入口。mongoose.connect('mongodb://localhost/test')— 发起异步连接,数据库为 test,不是 collection。await mongoose.connect(uri, options)— 等待初始连接成功;失败可 reject。mongoose.connect(uri, options).then(...)— 连接成功后执行回调;仍需处理失败。maxPoolSize: 5— 【现代对应】设置连接池上限,不是五个 JS 执行线程。replicaSet: 'myReplicaSetName'— 【现代对应】指定 replica set。mongoose.model('Cat', { name: String })— 以简写结构生成 Model,返回构造 / 操作入口。new Cat({ name: 'Tiger' })— 创建 Document,不立即插入。await kitty.save()— 校验并保存;成功后才能执行后续正常流程。new Schema({ username: { type: String, required: true } })— 定义字段结构与规则。index: { unique: true }— 声明唯一索引,不是普通 validator。
References & Middleware(p.9–11)
_creator: { type: Number, ref: 'Person' }— 保存 Number ID,populate 时使用 Person Model。fans: [{ type: Number, ref: 'Person' }]— 引用 ID 数组。Story.findOne({ title: 'Once upon a timex.' })— 构建查询,不保证存在结果。.populate('_creator')— 请求加载关联创建者;不是保存嵌入副本。.exec()— 执行 Query,返回 Promise。story._creator.name— 读取已加载文档字段;先确认 story / _creator 非 null。schema.pre('save', async function () {...})— 保存操作前执行 hook,普通函数中可使用文档 this。schema.post('save', function (doc) {...})— 【对应机制补充】成功保存后执行 hook。schema.pre('validate', function () {...})— 【补充】在校验前规范化字段。this.first_name.replace(/<(?:.|\n)*?>/gm, '')— 返回删除匹配片段后的字符串,未赋值时不修改原字段。validate: { validator(v) {...}, message: '...' }— 自定义校验与错误消息。/^\d{3}-\d{3}-\d{4}$/.test(v)— 返回布尔值,修正课件数字正则与完整匹配。message: '{VALUE} is not a valid phone number!'— 错误消息中的 VALUE 占位符会使用失败值。
Joi(p.12)
const Joi = require('joi')— 加载验证库。Joi.object({ ... })— 创建对象验证规则。Joi.string()— 要求字符串规则。.lowercase()— 默认转换模式下返回小写值。.alphanum()— 仅字母数字。.min(3).max(32)— 字符串长度边界,包含允许边界。.required()— 字段必需。.email()— 邮箱格式规则。.allow('')— 允许显式空字符串。.default('')— 缺失等默认触发情形使用空字符串。await schema.validateAsync(req.body)— 异步验证,返回验证 / 转换后的值;失败 reject。schema.validate(input)— 【补充】同步返回 value / error。schema.validateAsync(input, { convert: false })— 【补充】关闭自动转换;lowercase 不再直接替你转换。schema.validateAsync(input, { abortEarly: false })— 【补充】收集多个验证错误,方便表单 / API 返回。
【代码题】修正后的 Reference + Populate 完整结构
可能题目:
Define Person and Story models. Store the creator as a reference, populate it, and display the creator's name.
写法顺序:Schema → Model → 保存关联对象 → 保存 ID → 查询并 populate。
javascript
const mongoose = require('mongoose');
const { Schema } = mongoose;
const personSchema = new Schema({
_id: Number,
name: { type: String, required: true },
});
const storySchema = new Schema({
_creator: { type: Number, ref: 'Person' },
title: { type: String, required: true },
fans: [{ type: Number, ref: 'Person' }],
});
// ref 指向注册的 Model 名 Person。
const Person = mongoose.model('Person', personSchema);
const Story = mongoose.model('Story', storySchema);
async function main() {
await mongoose.connect('mongodb://127.0.0.1:27017/cs4288');
try {
// 示例按空测试数据库、首次运行理解。
// 重复插入相同 _id 会产生重复键错误。
const author = await Person.create({
_id: 1,
name: 'Alice',
});
const created = await Story.create({
title: 'Once upon a time.',
_creator: author._id, // 保存 ID,不是自动嵌入完整 author。
fans: [],
});
const story = await Story.findById(created._id)
.populate('_creator')
.exec();
if (!story) {
console.log('Story not found');
return;
}
// Story 可能存在,但关联 Person 已被删除。
console.log(story._creator?.name ?? 'Creator not found');
} finally {
// 一次性脚本结束时关闭;Web 服务通常复用连接。
await mongoose.disconnect();
}
}
main().catch(console.error);【代码题】Joi 校验要使用返回值
javascript
const Joi = require('joi');
const userInputSchema = Joi.object({
username: Joi.string()
.lowercase()
.alphanum()
.min(3)
.max(32)
.required(),
primary_email: Joi.string()
.lowercase()
.email()
.required(),
first_name: Joi.string().allow(''),
last_name: Joi.string().allow(''),
city: Joi.string().default(''),
password: Joi.string().min(5).required(),
});
// 假设位于 async Express handler 内。
const data = await userInputSchema.validateAsync(req.body);
// 后续使用 data,不是继续无条件使用原始 req.body。
// 密码还需经过密码 hash,不能把 data 整个原样存入用户集合。代码行为题:
- username 为
"Alice123":默认可转换为"alice123"。 - username 为
"alice_123":alphanum 不允许下划线。 - first_name 为
'':允许。 - first_name 缺失:未 required,通常允许。
- city 缺失:返回值获得
city: ''。 - password 长度 4:不通过。
- email 格式通过:不意味着已经邮件验证。
- 用户名唯一性:不由这一份 Joi Schema 自动保证。
4. True / False Traps(判断题陷阱)
- False —
A document database never needs schemas or validation.— 应用仍需一致性规则。(p.7–8) - False —
Mongoose is the MongoDB database server.— 是应用侧 ODM。(p.5) - False —
Defining a model immediately inserts a document.— 定义与写入不同。(p.5) - False —
new Cat(data) automatically saves data.— 需 save / create。(p.5) - True —
Code after await kitty.save() runs after that save succeeds.— 正常成功流程。(p.5) - False —
Calling connect without await means the connection is synchronous.— 可能存在操作缓冲。(p.5–6) - False —
The old nested connection options can always be copied into current Mongoose.— 版本不同。(p.6) - False —
Mongoose validation protects writes made through every possible database client.— 绕过 Mongoose 不执行其 hooks。(p.7–8) - False —
unique is a normal Mongoose validator.— 唯一索引约束。(p.8) - False —
A preliminary findOne check replaces the need for a unique index.— 并发下存在竞争。 - False —
A reference field must always use ObjectId.— 课件使用 Number。(p.9) - False —
ref names an arbitrary collection without requiring a corresponding model.— 课件语境指 Model 名。(p.9) - False —
populate permanently replaces the stored reference with an embedded document.— 改变的是返回结果的关联加载形态。(p.9) - False —
populate automatically creates missing related documents.— 不会。 - False —
story._creator.name is always safe after populate.— story 或关联可能 null。 - False —
A save hook automatically runs for every findOneAndUpdate operation.— 操作类型不同。(p.10) - False —
Arrow functions preserve document this in the same way as ordinary hook functions.— this 规则不同。(p.11) - False —
All Mongoose hooks are asynchronous.— init 是同步例外。(补充) - False —
/d{3}-d{3}-d{4}/ validates three groups of digits.— 匹配字母 d。(p.11;修正) - False —
An unanchored regex requires the entire input to match.— 可只匹配子串。 - False —
Removing tag-like substrings with the slide regex guarantees complete HTML sanitization.— 不是完整 sanitizer。(p.11) - False —
Joi validation necessarily leaves every value unchanged.— 默认可以转换。(p.12) - False —
allow('') makes a field required.— 允许空与必填不同。 - False —
default('') and allow('') mean the same thing.— 默认值与接受空字符串不同。 - False —
Joi.email verifies that the mailbox exists.— 格式校验。 - False —
Joi.alphanum allows underscores.— 通常不允许。 - False —
validateAsync resolves to a simple true/false result.— 成功返回验证后的值。 - False —
A password length rule automatically hashes the password.— 无关操作。
5. Exam Quick Reference(考前速查)
- 选型: memory KV / SQL / document / graph / search。(p.3)
- Schema → Model → Document → save,前三个动作不等于写库。(p.5)
- connect 异步;
/test、/foobar是数据库名。(p.6) - 旧 options: native_parser / server.poolSize / replset.rs_name 不直接照抄。
- Types: String / Number / Date / Buffer / Boolean / Mixed / ObjectId / Array。(p.8)
- required ≠ unique;unique 依赖 DB 索引。
- ref 指 Model;populate 关联加载,不改存储为嵌入。(p.9)
- p.9 修正: wait → await;Schema 需编译 Model 才查询。
- Hooks: pre → operation → post;普通函数使用文档 this;save 不覆盖所有 update。
- Phone: 课件 d 应为
\d;完整匹配加^/$。(p.11) - Joi: 先校验,使用返回 data;lowercase 可转换;allow 与 default 不同。(p.12)
- 代码题优先: Schema / unique / validator / populate / Joi → save。
Lecture 23 — Sessions
本章共 22 页。p.8–14 是同一个 session 流程的逐步图示;p.17 只引用课堂 Homework 4,没有附完整源码。外部 Session Store 在本课只讲架构,未展示具体库配置。
1. Core Concepts(核心概念)
Why Server-side State?(为何保存服务端状态)
The server should determine authentication state using trusted information.(p.3–7)
- 客户端提交
loggedIn: true不构成可信身份。 - 服务端验证身份后,建立后续请求可关联的会话。
- 客户端 UI 显示“已登录”不等于接口已完成认证。
- Session existence does not imply authentication. — 匿名用户也可以有 session。
- Session 可保存购物流程、临时偏好等,不只用于登录。
【补充】 这不表示服务端不能接受任何客户端凭据;重点是要验证凭据,而不是直接相信一个布尔值或用户名。
Session ID vs. Session Data(标识与内容)
The client carries a session identifier; the server stores the session data.(p.8–14)
课件典型流程:
- 初始请求到达。
- 服务器建立 session,生成 session ID。
- 响应通过 Cookie 等方式让客户端携带 ID。
- 后续请求带上该 ID。
- 服务器查找相应 session。
- 将恢复的 session 关联到 req。
Express-session 的典型模型:
- Cookie:session ID,通常还包含签名编码。
- Store:该 ID 对应的数据。
req.session:本次请求可以使用的 session 对象。- 数据并不是全部塞在 Cookie 里。
Important distinctions:
- Cookie 名不是 session ID。
- 签名不是加密。
- Session ID 本身不是用户密码。
- 获得 session ID 可能足以冒用会话,因此不能把它当无关紧要的普通编号。
req.session.data是课件示意字段,不是必须存在的固定内建业务结构。req.session.user同样是应用自定义字段。
HTTP Is Stateless; Sessions Add Application State
HTTP does not automatically remember the previous request's application context.
- 服务端可在 HTTP 之上用 session 关联请求。
- HTTP 协议无状态,不等于 Web 应用不能有状态。
- Session 不会自动让不同设备、不同浏览器共用同一个登录会话。
- 同浏览器中符合 Cookie 范围的标签页通常可能共用 session,不像 sessionStorage 那样按标签页独立。
Express-session Middleware(会话中间件)
课件 p.15:
javascript
app.use(session({
name: 'session',
secret: 'ohhellyes',
resave: false,
saveUninitialized: true,
cookie: {
path: '/',
httpOnly: false,
secure: false,
},
}));- 需要导入
express-session;不是 Express 默认自动打开的能力。 - 必须放在读取
req.session的 route 前。 - session middleware 创建 / 恢复会话,不负责自动校验用户名密码。
- 不需要为了它本身运行而额外安装 cookie-parser。
- 未指定 store 时,默认通常是 MemoryStore。
参考:Express — Session Middleware。
Configuration Semantics(配置含义)
name
The name identifies the session cookie, not the individual session value.
- 课件 Cookie 名为
session。 - 不表示所有用户都共用一个 session。
- 每个会话的 ID 值不同。
- 默认 Cookie 名通常为
connect.sid。 - 【补充】Cookie 不按端口隔离;同主机多个应用可能需要不同 Cookie 名。
secret
The secret signs the session-ID cookie.
- 用于 Cookie 签名 / 验证。
- 不等于把全部 session data 加密后存客户端。
- 不是用户密码。
- 多实例共享会话时需要兼容的 secret 配置。
- 课件字符串只是演示值,不应被当作项目固定要求。
resave: false
Do not force an unchanged session to be saved again on every request.
- 不代表禁止保存。
- 改了 session,仍可保存。
- 不代表 cookie 一定每次重发。
- store 的 touch / TTL 行为也会影响选项选择。
- 强制 resave 还可能带来并发覆盖问题,不能认为越多保存越正确。
saveUninitialized: true
Persist newly created sessions even if the application has not modified them.
- uninitialized 指新建且未被应用修改,不是“未登录”同义词。
- true 可能为匿名访问也保存 session / 发 Cookie。
- false 可以不保存新建未修改 session。
- 登录后写入 userId,即使 false,也不再属于“未修改的新 session”。
Cookie Flags(Cookie 属性)
| 配置 | 作用 | 不代表什么 |
|---|---|---|
path: '/' | 对站点路径范围生效 | 不表示所有域名都能读取 |
httpOnly: true | 禁止页面 JS 通过 document.cookie 读取 | 不阻止浏览器自动随请求发送 |
httpOnly: false | 不设置该限制 | 不是“Cookie 不工作” |
secure: true | 限制安全传输,常见为 HTTPS | 不等于 HttpOnly |
secure: false | 允许非 HTTPS 场景使用 | 不表示只能 HTTP、禁止 HTTPS |
maxAge | Express-session 配置单位为毫秒 | 与 HTTP Cache-Control max-age 秒不同 |
sameSite | 控制部分跨站 Cookie 发送行为 | 不替代全部认证 / CSRF 设计 |
【课件限定】p.15 的两个 false 是演示配置。
- 不是 session 工作必须关闭 HttpOnly / Secure。
- 本机 HTTP 演示可用 secure:false。
- HTTPS 部署通常应按实际代理 / HTTPS 架构配置 Secure。
- 如果 HTTPS 在反向代理终止,Express 的 trust proxy 配置可能影响安全 Cookie 判断。
- HttpOnly 不阻止 Cookie 自动发送,因此不单独解决 CSRF。
Session Lifecycle(生命周期)
Browser cookie lifetime and server-store lifetime are separate.
- 页面刷新:只要 Cookie 和服务端记录仍有效,可恢复 session。
- 关闭标签页:不必然销毁服务器 session。
- 关闭浏览器:Cookie / 恢复行为与配置有关,不能简单等同于立即清除服务器记录。
- 默认内存 store:进程重启可能丢 session,即使浏览器 Cookie 还在。
- 客户端删除 Cookie:不一定立即删除服务器存储中的旧 session。
- 服务端销毁 session:旧 Cookie 即使保留,也不再对应有效登录记录。
- Cookie 到期与 store TTL 不是同一个自动保证。
Login & Session Fixation(登录与会话固定)
课件 p.16:
javascript
req.session.regenerate(() => {
req.session.user = user;
res.status(200).send({
username: user.username,
primary_email: user.primary_email,
});
});Regenerate the session after successful authentication to reduce session-fixation risk.
正确顺序:
- 验证凭据。
- regenerate。
- 在新 session 写用户身份。
- 需要时显式 save。
- 返回响应。
Traps:
- regenerate 不验证密码。
- regenerate 是 callback 风格异步 API,不是默认返回 Promise。
- 写用户身份要在新 session 准备后进行。
- 重新生成不表示旧 session 所有字段自动保留。
- 【课件补全】callback 应处理 err。
- 可以只保存 userId,避免将完整用户文档、hash、salt 等全部放进 session。
- 自动 session 保存通常在响应结束附近发生;显式 save 可用于确保下一次请求 / 跳转前存储已完成。
Authorization Check(登录态检查)
课件:(p.16)
javascript
if (!req.session.user) {
res.status(401).send({ error: 'unauthorized' });
} else {
// ...
}- 这里检查的是应用设置的 session.user。
- 有 session 但没有 user,仍可视为未登录。
- 返回错误后要避免继续执行受保护逻辑。
res.send()不自动退出当前 JS 函数,常配合 return 或明确 else。- 【补充】401 通常表示缺失 / 无效认证;403 通常表示身份已识别但无权限。
Horizontal Scaling & Failure(水平扩展与故障)
课件 p.18–20:
Process-local session state makes request redistribution difficult.
- 用户先访问实例 A,session 数据存在 A 的内存。
- 下次负载均衡到 B,B 可能没有该 ID 的数据。
- A 故障或重启,A 中的 session 可能丢失。
- 多个 Node worker 也属于多个进程,不能假设普通内存自动共享。
- 同一 session ID 不会自动让实例之间交换数据。
External Session Store(外置会话存储)
课件 p.21–22:
Move session data to a shared store so web-server instances can retrieve it.
- Web server 实例访问同一份 session store。
- 请求可由不同实例处理。
- Web 进程重启不必导致 session 数据随进程消失,取决于 store。
- 实例仍需共享兼容的 Cookie 名、签名 secret、序列化配置等。
- 外置 store 的可用性、过期和并发仍要设计。
- Externalizing sessions does not eliminate all server-side state. — 只是把状态从本机进程移出去。
【补充】Sticky sessions are a different approach.
- 粘性会话将同客户端尽量路由到同实例。
- 可以缓解找不到本机 session,但实例故障仍可能丢会话。
- 不等价于共享 store,也不自动提供数据冗余。
2. Comparisons & Distinctions(易混淆概念对比)
Session-related Terms
| 名称 | 保存什么 / 做什么 | 主要位置 |
|---|---|---|
| Session ID | 查找会话的标识 | Cookie / 请求 |
| Session data | 用户 ID、业务临时状态等 | 服务端 store |
| Cookie name | Cookie 字段名,例如 cs4288.sid | Cookie 配置 |
| Secret | 签名依据 | 服务器配置 |
req.session | 当前请求可用的会话对象 | 请求处理上下文 |
| sessionStorage | 字符串键值、标签页会话隔离 | 浏览器 |
resave vs. saveUninitialized
| 配置 | 针对什么 | false 的含义 |
|---|---|---|
| resave | 已有 / 当前 session 未修改时的强制保存 | 不强制每次重写,不禁止保存修改 |
| saveUninitialized | 新建但未修改的 session | 不保存这种新空会话 |
| Cookie maxAge | 客户端 Cookie 有效期 | 不是是否保存 store 的总开关 |
Local Memory vs. Shared Store
| 维度 | 进程内存 | 外置共享 store |
|---|---|---|
| 多实例共享 | 不自动 | 可共享 |
| Web 进程重启 | 通常丢失 | 取决于外部 store |
| 负载均衡到其他实例 | 可能无记录 | 可查询相同记录 |
| 额外网络依赖 | 少 | 有 |
| 是否整个系统无状态 | 否 | 仍有 store 状态 |
Cookie Flag Distinctions
| 功能 | 对应设置 |
|---|---|
| 不让页面 JS 读 | HttpOnly |
| 限制安全传输 | Secure |
| 跨站发送限制 | SameSite |
| 路径范围 | Path |
| 客户端生命周期 | Max-Age / Expires |
| session ID 完整性 | secret 签名 |
| 服务器会话保存位置 | store |
3. APIs & Configurations(API 与配置速查)
课件 API(p.15–16)
const session = require('express-session')— 加载会话 middleware。app.use(session(options))— 在请求管线中创建 / 恢复 session,不启动端口。name: 'session'— 设置 Cookie 名,不是固定 session ID。secret: '...'— Cookie 签名 secret,不是用户密码或全数据加密 key。resave: false— 未修改时不强制重存,修改仍可保存。saveUninitialized: true— 保存新建但未修改的 session。cookie: { path: '/' }— 设置 Cookie 路径范围。cookie: { httpOnly: false }— 课件允许 JS 可见的演示配置。cookie: { secure: false }— 课件允许 HTTP 的演示配置。req.session.user = user— 修改当前会话业务字段,通常在响应流程中保存到 store;赋值本身不等于存储已完成。req.session.user— 读取已恢复的身份数据。req.session.regenerate(callback)— 异步建立新 SID / Session,callback 参数为 err。res.status(401).send({ error: 'unauthorized' })— 返回认证失败响应,不自动退出当前函数。res.status(200).send({ username, primary_email })— 登录成功返回公开信息,不必返回整个用户对象。
必要补充
req.sessionID— 当前 session 的 ID。req.session.save(callback)— 显式写入 session store,完成后 callback(err)。req.session.destroy(callback)— 销毁服务端 session,并取消当前 req.session;不等于自动清掉客户端 Cookie。res.clearCookie('cs4288.sid', { path: '/' })— 要求客户端清除对应 Cookie,范围应匹配。cookie: { maxAge: 30 * 60 * 1000 }— Cookie 有效期 30 分钟,单位毫秒。cookie: { httpOnly: true, sameSite: 'lax' }— 常见浏览器 Cookie 设置。store: sharedStore— 使用已创建的共享 store 对象;课件未提供具体实现。app.set('trust proxy', 1)— 在明确代理拓扑下信任一层代理;不是所有部署都无条件使用。fetch('/login', { method: 'POST', credentials: 'include', ... })— 跨 origin Cookie 场景常需 include;服务器也需正确配置 CORS 与 Cookie 条件。fetch('/me')— 同源请求默认通常携带符合条件的同源 Cookie,不必手动读取 HttpOnly Cookie。
【代码题】完整 Session 微型服务
可能题目:
Implement login, a protected profile route, and logout using server-side sessions. Regenerate the session after successful authentication.
写题顺序:
- body parser。
- session middleware。
- 验证密码。
- regenerate → 写 userId → save。
- 受保护接口检查 session。
- logout destroy + clear Cookie。
下面为独立演示服务,使用一个内存测试用户和默认 MemoryStore;密码验证通过 Node scrypt 演示。真实项目可将查用户部分替换为 Lecture 22 的 Mongoose 查询。
bash
npm install express express-session
node server.cjsjavascript
const express = require('express');
const session = require('express-session');
const {
randomBytes,
scrypt,
timingSafeEqual,
} = require('node:crypto');
const { promisify } = require('node:util');
const deriveKey = promisify(scrypt);
async function main() {
// 演示用户:exam / exam-demo-only。
// hash 和 salt 留在服务器,不返回给客户端。
const user = {
id: 'u1',
username: 'exam',
primary_email: 'exam@example.com',
salt: randomBytes(16).toString('hex'),
};
user.hash = await deriveKey(
'exam-demo-only',
user.salt,
64
);
const app = express();
app.use(express.json());
app.use(session({
name: 'cs4288.sid',
// 单进程演示可生成随机 secret。
// 多实例需要兼容且稳定的共享配置,不能各自随机。
secret:
process.env.SESSION_SECRET ||
randomBytes(32).toString('hex'),
resave: false,
saveUninitialized: false,
cookie: {
path: '/',
httpOnly: true,
secure: false, // 本例运行在本机 HTTP。
sameSite: 'lax',
maxAge: 30 * 60 * 1000,
},
}));
// 认证相关响应不放进浏览器/共享响应缓存。
app.use((req, res, next) => {
res.set('Cache-Control', 'no-store');
next();
});
const wrap = fn => (req, res, next) => {
return Promise.resolve()
.then(() => fn(req, res, next))
.catch(next);
};
app.post('/login', wrap(async (req, res, next) => {
const { username, password } = req.body || {};
if (
typeof username !== 'string' ||
typeof password !== 'string'
) {
return res.status(400).json({
error: 'username/password required',
});
}
if (username !== user.username) {
return res.status(401).json({
error: 'Invalid credentials',
});
}
const candidate = await deriveKey(
password,
user.salt,
64
);
if (!timingSafeEqual(candidate, user.hash)) {
return res.status(401).json({
error: 'Invalid credentials',
});
}
// 验证成功后,先换 session 身份。
req.session.regenerate(err => {
if (err) return next(err);
// 只保存业务所需 ID,不把 hash/salt 全塞进去。
req.session.userId = user.id;
// callback 风格,不能直接当 Promise await。
req.session.save(err => {
if (err) return next(err);
res.json({
username: user.username,
primary_email: user.primary_email,
});
});
});
}));
function requireLogin(req, res, next) {
if (req.session.userId !== user.id) {
return res.status(401).json({
error: 'unauthorized',
});
}
next();
}
app.get('/me', requireLogin, (req, res) => {
res.json({
id: user.id,
username: user.username,
});
});
app.post('/logout', (req, res, next) => {
req.session.destroy(err => {
if (err) return next(err);
// 销毁服务端数据与清客户端 Cookie 分别做。
res.clearCookie('cs4288.sid', { path: '/' });
res.status(204).end();
});
});
app.use((err, req, res, next) => {
if (res.headersSent) return next(err);
console.error(err);
res.status(500).json({
error: 'Internal server error',
});
});
app.listen(8080, '127.0.0.1', () => {
console.log('http://127.0.0.1:8080');
});
}
main().catch(err => {
console.error(err);
process.exitCode = 1;
});请求验证顺序:
bash
curl -i http://127.0.0.1:8080/me
curl -i -c /tmp/cs4288-cookies.txt \
-H 'Content-Type: application/json' \
-d '{"username":"exam","password":"exam-demo-only"}' \
http://127.0.0.1:8080/login
curl -i -b /tmp/cs4288-cookies.txt \
http://127.0.0.1:8080/me
curl -i -b /tmp/cs4288-cookies.txt \
-X POST http://127.0.0.1:8080/logout- 第一次 me:401。
- 登录:生成新 session,返回 Cookie。
- 带 Cookie 访问 me:成功。
- logout:删除服务端会话,204。
- 再使用旧 ID:不再得到已登录身份。
与数据库接线时替换哪部分:
javascript
const user = await User.findOne({ username }).exec();之后验证数据库中的密码 hash,再执行相同的 regenerate / save 流程。
不要写成:
javascript
req.session.userId = req.body.userId;然后就认为完成了身份验证。
4. True / False Traps(判断题陷阱)
- False —
A client-provided loggedIn flag proves authentication.— 服务端需验证。(p.5) - False —
Having a session means the user is logged in.— 匿名 session 也存在。 - True —
The server can use a session ID to look up server-side state.— 核心流程。(p.8–14) - False —
express-session stores all session data in the cookie.— 通常只带 ID / 签名。(p.15;补充) - False —
The name option sets every client's session ID to the same value.— name 是 Cookie 名。 - False —
The session secret encrypts all session data into the cookie.— 用于签名,不是此模型。 - False —
resave:false disables saving modified sessions.— 不强制保存未修改 session。 - False —
saveUninitialized:false prevents authenticated sessions from being saved.— 写身份后已修改。 - False —
Uninitialized is simply another word for logged out.— 新建未修改与认证状态不同。 - False —
httpOnly prevents cookies from being sent with HTTP requests.— 防 JS 读,不防自动发送。 - False —
secure:false means the cookie cannot be used over HTTPS.— 只是未要求安全传输。 - False —
secure:true works the same over ordinary local HTTP.— 受 HTTPS 条件限制。 - False —
Session cookie maxAge uses seconds like Cache-Control max-age.— Express-session 选项用毫秒。 - False —
Refreshing the page always destroys the server session.— 有效 Cookie / store 可恢复。 - False —
Closing a tab necessarily deletes server-side session data.— 两层生命周期不同。 - False —
A browser cookie guarantees an in-memory session survives server restart.— 内存可能丢失。 - True —
Regenerating the session after authentication helps prevent session fixation.— p.16。 - False —
regenerate automatically validates the username and password.— 应先验证。 - False —
await req.session.regenerate() necessarily waits for completion.— 默认 callback API。 - False —
Regeneration always preserves all old session fields.— 新 session。 - False —
Destroying a session automatically removes every related browser cookie.— 通常另行 clearCookie。 - False —
MemoryStore is automatically shared across Node processes.— 进程本地。 - False —
A load balancer automatically copies session data between servers.— 无此保证。(p.18–20) - True —
A shared session store allows multiple web instances to retrieve session data.— p.21–22。 - False —
Externalized sessions make the entire system free of server-side state.— 状态转移到 store。 - False —
Sticky sessions provide the same failure behavior as a redundant shared store.— 不同方案。(补充)
5. Exam Quick Reference(考前速查)
- Session flow: generate ID → Cookie → next request → lookup store → req.session。(p.8–14)
- Cookie ID ≠ session data。
- name: Cookie 名;secret: 签名;不是密码 / 全数据加密。
- resave:false: 不强制重存未修改 session。
- saveUninitialized:false: 不保存新建未修改 session。
- HttpOnly: 防 JS 读;Secure: 安全传输;SameSite: 跨站发送。
- maxAge: Express-session 毫秒;HTTP cache max-age 秒。
- Login: 验证 → regenerate → 写 userId → save → 响应。
- Logout: destroy store session + clear Cookie。
- 401: 缺失 / 无效认证;403: 已认证但无权限。
- Scaling: 本机 session 阻碍切换实例;外置共享 store。(p.18–22)
- 代码题: middleware 顺序、regenerate callback、return 错误分支、受保护 route。
Lecture 24 — RESTful APIs
本章共 33 页。多页是同一内容的逐步高亮。
最重要的客观题区域:HTTP method 的 safe / idempotent、缓存头、Accept vs. Content-Type。
p.17 的 Cache-Control 示例和 no-cache 解释需要修正,不能原样背。
1. Core Concepts(核心概念)
REST — Representational State Transfer
REST is an architectural style for interactions with resources and their representations.(p.3)
【课件修正】正确全称是 Representational State Transfer,不是 Representative State Transfer。
- 关注 resource / data / object 的交互。
- 不以特定 UI 页面作为 API 的唯一组织方式。
- API 可以独立于某一个前端界面设计。
- REST 不是 JS 框架、序列化格式或 npm 包。
- JSON API 不因返回 JSON 就自动满足 REST。
- REST 不要求只能使用 JSON;representation 可以有不同媒体类型。
Separate Presentation from Data(表现与数据分离)
课件 p.4–5:
- Static server:HTML、SPA、images 等。
- API server:数据资源。
- Your API can be a standalone product. — API 可由多个客户端使用。
【课件限定】Logical separation does not require two physical machines.
- 可以同进程 / 同域,也可以不同服务 / 不同域。
- 不同 origin 时需要处理相应跨域机制。
- API 与 UI 解耦,不表示数据不能用 HTML 表示,也不表示 SPA 不再需要静态文件。
REST Constraints(REST 约束)
课件 p.6:
- Client–server
- Layered
- Stateless
- Cacheable
- Client-executable code
| Constraint | 英文考试表述 | 中文 |
|---|---|---|
| Client–server | Separate client and server responsibilities. | 职责分离 |
| Layered system | A client need not know all intermediary layers. | 可有代理、缓存、负载均衡等 |
| Stateless | Each request carries the context needed to understand it. | 不依赖隐含的前次请求会话上下文 |
| Cacheable | Responses indicate whether and how they can be reused. | 有明确缓存语义 |
| Code-on-demand | Servers may supply executable code to clients. | 可选地发送客户端执行代码 |
【课件补全】Uniform interface is a central REST constraint omitted from this list.
它强调资源识别、通过表示操作资源、自描述消息等统一交互方式。
【课件限定】Code-on-demand is optional.
- 不需要每个 API 响应都返回 JS。
- 不需要每个 REST 客户端都执行服务器代码。
参考:Fielding — REST Architectural Style。
Statelessness(无状态)
Stateless does not mean the server stores no data.(p.7,精确定义补充)
可以保存:
- 用户数据库。
- 订单、游戏、文档等资源。
- 服务器配置和资源状态。
严格 REST stateless 主要避免:
- 必须依赖服务器保存的某个客户端对话 / 会话上下文,才能理解当前请求。
课件认为以下内容可能让无状态难以实现:(p.7)
- Authentication
- Multi-step processes
- Multi-party interactions
- Logic simplification
- Performance trade-offs
与 Lecture 23 的关系:
- Lecture 23 的 session 是实用的会话状态设计。
- 将 session 从 Web 内存挪到共享 store,有利于 Web 实例扩展。
- 但共享 store 中仍是 session state,不自动变成严格 REST stateless。
- 认证并不必然要求服务端会话;关键是具体凭据与协议设计。
- 课件在讨论工程取舍,不是在证明所有认证 API 都无法无状态。
Resources, Nouns & Methods(资源名词与操作动词)
Use nouns to identify resources and HTTP methods to express operations.(p.8–15、19–26)
课件示例:
POST /v1/usersPOST /v1/gameGET /v1/game/18d8wjs892DELETE /v1/game/1198f91ns3GET /v1/user/heminggs/gamesGET /v1/user/heminggs/game/18d8wjs892
关键区分:
- path:什么资源。
- method:对它做什么。
- query:如何筛选 / 排序 / 分页 / 选择字段。
- body:提交的 representation 或操作内容。
Nested vs. direct resource URLs:
/users/alice/games:某用户关联的游戏集合。/games/g1:直接定位游戏。/users/alice/games/g1:在用户上下文下定位游戏。- 不是所有资源都必须嵌套在用户路径下面。
- URI 层级不强制等于数据库嵌入结构。
- 若嵌套 route 表达归属关系,handler 应验证关系,不是只读最后一个 ID。
【课件限定】Singular/plural naming is an API convention, not an HTTP protocol law.
- 课件混用 user/users、game/games。
- 实际设计优先保持一致。
- 不能答“所有 REST API 都必须有固定相同的复数拼写”。
Safe Methods(安全方法)
A safe method does not request a change to application state.(p.10–15)
课件重点:
- GET
- HEAD
【课件修正】“Nothing can change” is too absolute.
- 服务端可记录访问日志、统计等附带行为。
- safe 指客户端没有请求业务状态变更。
- 不应把“删除用户”“提交付款”藏在 GET route。
- 方法名称不会阻止错误实现:写成 GET 的 handler 仍可能错误地删数据。
- 【补充】HTTP 还定义 OPTIONS、TRACE 为 safe,课件列表不是完整清单。
Idempotent Methods(幂等方法)
Repeating the same request has the same intended effect as making it once.(p.12–15)
课件重点:
- PUT
- DELETE
【补充】Safe methods are also idempotent.
- GET / HEAD 不是因为课件分栏就“不幂等”。
- safe 与 idempotent 是不同维度,不是互斥分类。
- 幂等不等于每次响应字节完全一样。
- 幂等不等于状态码必须一样。
- 幂等不等于第一次就不能改变状态。
Examples:
- 重复 PUT 相同 representation 到同一资源:预期资源状态相同。
- 重复 DELETE 同一资源:最终仍是已删除。
- 第一次 DELETE 204,第二次 404,不因此自动失去幂等语义。
- 将余额加 10,重复会继续增加,通常不幂等。
- 把余额设为 100,在相同条件下重复通常可幂等。
参考:HTTP Semantics、MDN — Idempotent。
HTTP Method Roles(HTTP 方法职责)
| Method | 核心语义 | Safe | Idempotent |
|---|---|---|---|
| GET | 获取 representation | 是 | 是 |
| HEAD | 与 GET 类似,但无响应正文 | 是 | 是 |
| PUT | 在已知 URI 创建 / 替换资源表示 | 否 | 是 |
| DELETE | 请求移除目标资源关联 | 否 | 是 |
| POST | 按目标资源定义处理提交内容 | 否 | 不保证 |
| PATCH | 【补充】部分修改 | 否 | 不保证,取决于修改方式 |
PUT traps:
- 不只是“任何更新操作”的别名。
- 可在目标不存在时创建资源,不一定只能修改已有资源。
- 若用 PUT 每次累加分数,就偏离其预期幂等语义。
- HTTP 不自动替你的数据库执行 replacement;实现仍由服务端负责。
POST traps:
- 课件写 application-specific behavior。
- 常用于创建,但不限定只能创建。
- 默认语义不保证幂等。
- 应用可以设计重复检测等机制,但不能因此说所有 POST 都幂等。
- 不要说“POST 因为在 body 传参就自动安全 / 加密”。
HEAD traps:
- 不返回响应正文。
- 可用于查看资源相关元信息 / 状态。
- 不意味着服务器完全不执行资源查找或计算。
- 不等于“只判断存在,其他 HTTP 语义都不用管”。
API Versioning(版本选择)
课件 p.16 提供三种方式:
| 方式 | 示例 |
|---|---|
| Path version | GET /v1/users/heminggs |
| Accept media type | Accept: application/vnd.foo.v1+json |
| Custom header | X-API-Version: 1 |
- API 演进时应有清晰兼容策略。
- 版本不必只放 URL。
- Accept 可以同时表达媒体类型与版本。
- 自定义 header 不是 HTTP 自动理解的业务版本,需要服务器实现。
- 版本号不是认证信息。
- 不要求每个系统同时实现全部三种方式。
【补充】Version / format negotiation affects caching.
- 同 URL 因 Accept 返回不同表示,缓存需区分。
- 可用
Vary: Accept。 - 如果由自定义版本头决定表示,也需考虑对应 Vary。
- 只变响应数据、不变 URL,又不配置缓存区分,可能混用表示。
Accept vs. Content-Type(最重要 Header 对比)
课件 p.18:
- Accept:客户端愿意接收什么格式。
- Content-Type:当前消息正文实际是什么格式。
Both requests and responses can have Content-Type when they contain relevant content.
请求:
http
POST /v1/users
Accept: application/json
Content-Type: application/json- Accept:希望得到 JSON 响应。
- 请求 Content-Type:发送的是 JSON body。
响应:
http
Content-Type: application/json- 响应 body 的格式。
Priority:
Accept: application/json, application/xml表示可接受多种类型。- 显式优先级可用 q 值,例如
application/json;q=1, application/xml;q=0.5。 - 不要只凭逗号先后推断所有优先级。
.json/.xml后缀是课件提出的替代约定,不是 REST 必须形式。
【补充】Common mismatch statuses:
- 406:服务端无法提供可接受表示。
- 415:不支持请求正文的媒体类型。
- 不能只凭设置 Accept 就强制任何服务器必须支持该格式。
参考:MDN — Accept。
Collection vs. Individual Resource(集合与单资源)
课件 p.27:
GET /v1/users:用户集合。GET /v1/user/heminggs:单用户。
A collection can be empty without the collection endpoint being missing.
- 成功查询零个用户,常见返回
[]或{ items: [] }。 - 单用户不存在,常见 404。
- 不必因集合暂时无数据就返回 404。
- 课件的数组示意缺少部分逗号、使用弯引号,不是严格 JSON 范本。
- REST 不规定集合响应只能是裸数组;可有分页 metadata 的包装对象。
Query Parameters(查询能力)
课件 p.28–32:
- filterBy
- pagination
- start page
- size limit
- sort order
- fields
完整示例:
http
GET /v1/users?q=h&limit=50&start=3&sort=asc&fields=first,last,dob| 参数 | 课件意图 | 必须明确的边界 |
|---|---|---|
| q | 搜索 / 筛选 | 前缀、子串、全文等需 API 定义 |
| limit | 最大返回数量 | 不是默认返回总集合 |
| start | 分页起点 | 页码还是 offset、从 0 还是 1,需明确 |
| sort | 排序方向 | 按哪个字段排序也需定义 |
| fields | 选择返回字段 | 服务端仍须白名单与权限检查 |
重要陷阱:
- Express 不会仅凭参数名自动完成数据库筛选。
- query 输入需要检查类型和数值范围。
- 不直接
Model.find(req.query)。 - 稳定分页通常需要确定的排序规则。
fields=...不应允许越权读取 hash / salt 等字段。- query projection 不会删除数据库原字段。
Caching — Freshness vs. Validation(新鲜度与再验证)
A fresh cache entry can be reused without contacting the origin server.(p.17)
两种不同路径:
- Freshness / fresh hit:在允许复用的有效期内直接使用,可能不发网络请求。
- Validation:带条件请求问服务器是否变化,可能收到 304。
- 有缓存不等于每次都不联网。
- 304 仍然发生了请求。
- 缓存可以发生在浏览器、代理、CDN 等层。
- 可缓存性与 safe / idempotent 不完全等价。
- 不能说所有 GET 响应一定缓存,也不能说 POST 响应在 HTTP 中绝对不可能缓存。
Cache-Control(课件重点修正)
课件 p.17 写 Cache-Control: 360。
【课件修正】正确新鲜度示例:
http
Cache-Control: max-age=360- max-age 单位为秒。
- 表示允许的新鲜度时间,不是命令客户端必定保存。
- 还有其他 cache directives,不只一个数字。
no-cache vs. no-store:
| Directive | 精确含义 |
|---|---|
max-age=360 | 在相关条件满足时,360 秒内可按新鲜缓存复用 |
no-cache | 可以存,但复用前必须成功再验证 |
no-store | 不应存储该请求 / 响应的相应缓存内容 |
private | 不允许共享缓存存储,私有缓存仍可 |
public | 明确允许共享缓存按规则处理 |
【课件修正】no-cache does not mean “caching is unsupported” or “never store.”
- “不能保存”对应 no-store 的意图。
- private 也不是加密。
- no-store 不保证删除应用任意 localStorage 中自行复制的数据。
参考:MDN — Cache-Control、HTTP Caching。
ETag(表示校验器)
An ETag identifies a version of a representation.(p.17)
http
ETag: "686897696a7c876b7e"- opaque value,不要求客户端理解其内部结构。
- 不必须是某一种 hash。
- 不等于资源 ID。
- 不等于过期时间。
- 课件强调区分媒体类型:JSON / XML 等不同表示不应被错误地当成相同强表示版本。
- 【课件限定】把 media type 加进 hash 是实现策略,不是 ETag 必须使用的唯一算法。
【补充】Conditional GET:
http
If-None-Match: "686897696a7c876b7e"- 当前表示匹配时,GET / HEAD 可返回 304。
- 304 无响应正文,客户端复用已有 body。
- 不匹配则正常返回新表示,例如 200。
- ETag 本身不表示“在接下来 360 秒都不要请求”;新鲜度由 cache policy 等决定。
参考:MDN — ETag。
Date, Expires, Last-Modified, Pragma(其他缓存相关头)
| Header | 正确理解 | 课件限定 |
|---|---|---|
| Date | 消息产生时间的 HTTP-date | 不是用户电脑当前时间,也不是资源修改时间 |
| Expires | 绝对的新鲜度到期时间 | 不要求有 max-age 才能存在 |
| Last-Modified | 表示 / 资源最近修改时间 | 不是响应生成时间 |
| Pragma | 旧 HTTP 缓存兼容指令 | 不能当成所有响应必须同步设置的现代规则 |
Expires:
- 有
Cache-Control: max-age时通常由 max-age 优先。 - 可以单独提供 Expires。
- 课件“必须有 max-age 才有 Expires”不是协议要求。
- 过期不表示缓存文件必须立即删除,只是通常不能直接当 fresh 使用。
Last-Modified:
- 客户端可用
If-Modified-Since再验证。 - 时间精度与更新方式可能不如 ETag 精细。
- 如果同时有适用的 If-None-Match,条件处理存在优先规则,不是随便选一个。
Pragma:
Pragma: no-cache主要用于旧请求缓存兼容。- 不是只要响应 Cache-Control:no-cache 就必须再加 Pragma 的普遍要求。
参考:Date、Expires、Last-Modified、Pragma。
2. Comparisons & Distinctions(易混淆概念对比)
Safe vs. Idempotent vs. Cacheable
| 概念 | 问的是什么 | 反例 / 陷阱 |
|---|---|---|
| Safe | 是否请求业务状态变化 | 日志变化不必然破坏 safe |
| Idempotent | 重复同一请求是否增加预期效果 | 状态码不同不必然破坏幂等 |
| Cacheable | 响应能否按规则存储和复用 | 不是 GET 就一定缓存 |
PUT vs. POST vs. PATCH
| 项目 | PUT | POST | PATCH |
|---|---|---|---|
| 典型用途 | 已知 URI 的创建 / 替换 | 创建或资源定义的处理 | 局部修改 |
| 幂等保证 | 有 | 默认不保证 | 默认不保证 |
| 示例 | 将配置设为 X | 创建新订单 | 设置一个字段 / 执行 patch |
| 常见误区 | 当作任意累加更新 | 认为只能创建 | 认为天然幂等 |
Header Roles
| Header | 方向 / 职责 |
|---|---|
| Accept | 请求:希望接收什么表示 |
| Content-Type | 当前消息 body 的格式 |
| ETag | 响应:表示版本校验器 |
| If-None-Match | 请求:使用 ETag 条件验证 |
| Last-Modified | 响应:修改时间 |
| If-Modified-Since | 请求:按时间验证 |
| Cache-Control | 缓存指令 |
| Expires | 绝对新鲜度时间 |
| Vary | 缓存需按哪些请求头区分表示 |
Caching Cases
| 情况 | 是否可保存 | 复用前是否一般需要请求 |
|---|---|---|
| 可缓存且仍 fresh | 可以 | 通常不需要 |
no-cache | 可以 | 需要成功验证 |
no-store | 不应存 | 不应依赖保存的响应复用 |
private, max-age=60 | 私有缓存可按规则存 | fresh 时可直接复用 |
| 条件请求返回 304 | 已有 body 可继续用 | 这次已经发出了请求 |
3. APIs & Configurations(API 与配置速查)
HTTP Calls(p.8、19–27)
HEAD /v1/users/heminggs— 获取对应状态 / 元信息,不返回响应正文。POST /v1/game— 按课件创建 / 处理游戏资源,非默认幂等。DELETE /v1/game/1198f91ns3— 删除指定资源,幂等但不 safe。GET /v1/users?q=hem&sort=asc&limit=50— 查询用户集合。POST /v1/users— 对用户集合提交创建请求。GET /v1/user/heminggs/games— 用户关联的游戏集合。GET /v1/user/heminggs/game/18d8wjs892— 用户上下文中的一个游戏。GET /v1/game/18d8wjs892— 直接定位游戏。GET /v1/users— 集合。GET /v1/user/heminggs— 单资源。
Versioning & Representation(p.16、18)
/v1/users/heminggs— 版本放路径。Accept: application/vnd.foo.v1+json— 用 vendor media type 选择版本 / 格式。X-API-Version: 1— 自定义版本头,需服务器实现。Accept: application/json,application/xml— 可接受多种响应格式。Accept: application/json;q=1,application/xml;q=0.5— 【补充】显式偏好 JSON。Content-Type: application/json— 当前消息内容为 JSON。Vary: Accept— 【补充】共享缓存区分不同 Accept 表示。Vary: X-API-Version— 【补充】自定义版本选择影响表示时应考虑的缓存区分。
Cache Headers(p.17)
ETag: "686897696a7c876b7e"— 表示版本标识,不是有效期。If-None-Match: "686897696a7c876b7e"— 【补充】请求进行 ETag 验证。Date: Sun, 06 Nov 1994 08:49:37 GMT— 消息产生时间示例。Cache-Control: max-age=360— 修正课件,360 秒新鲜度。Cache-Control: no-cache— 允许存,复用前验证。Cache-Control: no-store— 【补充】不存储。Cache-Control: private, max-age=60— 【补充】私有缓存 60 秒新鲜度。Expires: Sun, 06 Nov 1994 08:55:37 GMT— 相对上方 Date 的 360 秒后示例;不是所有响应必须配套设置。Pragma: no-cache— 旧兼容指令,不等于现代响应缓存的完整配置。Last-Modified: Sun, 06 Nov 1994 08:49:37 GMT— 资源 / 表示修改时间。If-Modified-Since: Sun, 06 Nov 1994 08:49:37 GMT— 【补充】按修改时间再验证。304 Not Modified— 条件 GET / HEAD 的未修改响应,无正文。
Collection Queries(p.28–32)
q=h— 搜索条件,具体语义由 API 文档决定。limit=50— 最大返回条数。start=3— 分页起点,课件未精确定义页码基准 / offset 规则。sort=asc— 升序方向,仍需明确排序字段。fields=first,last,dob— 请求字段子集,服务端需白名单。GET /v1/users?q=h&limit=50&start=3&sort=asc&fields=first,last,dob— 将筛选、分页、排序、字段选择组合在同一个集合资源查询中。
Express 对应写法(补充,便于代码题)
app.get('/v1/users', handler)— 注册集合读取。app.get('/v1/users/:username', handler)— 注册单用户读取。app.post('/v1/users', handler)— 注册用户创建。app.put('/v1/games/:id', handler)— 实现已知 URI 的创建 / 替换。app.delete('/v1/games/:id', handler)— 实现删除。req.query.limit— 原始查询输入,需验证转换。req.get('Accept')— 读取请求 Accept。res.type('application/json')— 设置响应媒体类型,不单独完成响应。res.vary('Accept')— 添加 Vary。res.set('Cache-Control', 'public, max-age=60')— 设置缓存策略。res.set('ETag', tag)— 设置校验器。req.fresh— 在当前响应校验器和请求条件下判断 fresh,适合条件响应判断。res.status(304).end()— 无正文完成 304。res.status(201).location('/v1/users/alice').json(user)— 创建成功,Location 指向新资源;location 本身不跳转。res.status(204).end()— 成功但无正文。res.status(404).json({ error: 'Not found' })— 单资源不存在。
【代码题】完整 GET + ETag + 304 示例
可能题目:
Implement a GET resource endpoint that supports a cache lifetime and conditional requests using ETag.
顺序:找资源 → 生成表示 → 生成校验器 → 设置缓存头 → 判断条件 → 304 或正文。
javascript
const express = require('express');
const { createHash } = require('node:crypto');
const app = express();
// 公开资源示例,无个性化数据。
const games = new Map([
['g1', { id: 'g1', title: 'Chess' }],
]);
app.get('/v1/games/:id', (req, res) => {
const game = games.get(req.params.id);
if (!game) {
return res.status(404).json({ error: 'Not found' });
}
// 这里把最终 JSON 文本作为表示。
const body = JSON.stringify(game);
// ETag 是实现策略,本例用正文 hash。
const tag =
'"' +
createHash('sha256').update(body).digest('hex') +
'"';
res.set('Cache-Control', 'public, max-age=60');
res.set('ETag', tag);
res.type('application/json');
// 必须先设置当前响应 ETag,再判断请求缓存条件。
// 不自行用简单字符串相等去代替完整 If-None-Match 语义。
if (req.fresh) {
return res.status(304).end();
}
return res.send(body);
});
app.listen(8081, '127.0.0.1', () => {
console.log('http://127.0.0.1:8081');
});执行理解:
- 首次 GET:200 + JSON body + ETag。
- 缓存允许且仍 fresh:浏览器可能直接复用,根本不请求服务器。
- 需要再验证时:客户端发送 If-None-Match。
- 表示相同:304,无 body。
- 表示变化:新 ETag + 200 + 新 body。
- 如果使用不同表示格式,需正确区分表示与缓存键。
- 这段 public cache 示例不应直接套在用户私密
/me响应上。
【设计题】用户 API 应如何组织
| 需求 | 示例 |
|---|---|
| 用户集合 | GET /v1/users |
| 查询用户 | GET /v1/users?q=alice&limit=20 |
| 一个用户 | GET /v1/users/alice |
| 创建用户 | POST /v1/users |
| 替换用户可写表示 | PUT /v1/users/alice |
| 删除用户 | DELETE /v1/users/alice |
| 用户游戏集合 | GET /v1/users/alice/games |
| 直接读取游戏 | GET /v1/games/g1 |
不该机械写成:
GET /deleteUser?id=aliceGET /createGame- 为所有操作统一使用 GET。
- 因为是 REST,就忽略认证 / 字段权限 / 错误状态。
状态码补充速查:
| Code | 常见用途 |
|---|---|
| 200 | 成功并返回表示 |
| 201 | 创建成功 |
| 204 | 成功,无正文 |
| 304 | 条件请求未修改,无正文 |
| 400 | 请求格式 / 参数错误 |
| 401 | 认证缺失 / 无效 |
| 403 | 无访问权限 |
| 404 | 目标不存在 |
| 406 | 无可接受响应表示 |
| 409 | 资源冲突,例如唯一键冲突 |
| 415 | 不支持请求媒体类型 |
| 500 | 服务器错误 |
状态码表是理解 API 设计所需补充,不是这份 PPT 逐项列出的表。
4. True / False Traps(判断题陷阱)
REST / Architecture / Methods
- False —
REST stands for Representative State Transfer.— 正确为 Representational。(p.3;修正) - False —
Any API returning JSON is automatically RESTful.— 还涉及架构约束。 - False —
REST requires JSON as the only representation format.— 可有其他媒体类型。 - True —
Presentation and data access can be separated.— p.4–5。 - False —
Separating static and API responsibilities requires two physical servers.— 逻辑分离不强制物理分离。 - False —
Code-on-demand is mandatory for every REST API response.— 可选约束。(p.6;限定) - False —
Stateless means the server cannot store users or orders.— 资源状态可保存。 - False —
Moving sessions to Redis or MongoDB automatically satisfies strict REST statelessness.— session state 仍存在。 - True —
The path identifies a resource while the HTTP method expresses the operation.— 核心设计。(p.8–26) - False —
GET should be used to delete resources because query parameters are convenient.— 违反 safe 语义。 - False —
A safe request can never cause any logging or accounting change.— 附带行为与请求业务效果不同。(p.11;修正) - False —
GET and HEAD are not idempotent because the slides list PUT and DELETE separately.— safe methods 也幂等。 - False —
An idempotent request cannot change server state.— PUT / DELETE 可以改变。 - False —
Idempotency requires identical responses and status codes on retries.— 看预期效果。 - True —
DELETE can remain idempotent even if a later attempt returns 404.— 最终删除效果未增加。 - False —
PUT can only update an existing resource.— 可在已知 URI 创建。 - False —
POST is guaranteed to be idempotent.— 默认不保证。(p.15) - False —
POST can only create resources and never perform other processing.— application-specific。 - False —
PATCH is always idempotent.— 取决于 patch。 - False —
HEAD returns the same response body as GET.— 不返回正文。 - False —
Using POST automatically encrypts request data.— 加密依赖 HTTPS 等。
Version / Resources / Queries
- False —
API versions must appear in the URL path.— 课件还有 Accept / custom header。(p.16) - False —
Accept and Content-Type express the same thing.— 接收偏好与当前 body 格式不同。(p.18) - False —
Content-Type is only a response header.— 请求 body 也有媒体类型。 - False —
Comma order alone always defines Accept preferences.— 可用 q 值等规则。 - False —
Nested URI paths force embedded database documents.— API 与物理存储不一一对应。 - False —
REST universally requires one fixed singular/plural spelling.— 约定一致性问题。 - False —
An empty successful collection query must return 404.— 可返回空列表。 - False —
The server automatically implements pagination because limit is present in the URL.— handler 需实现。 - False —
start=3 has one universal meaning across REST APIs.— 需定义页码 / offset。 - False —
fields=hash,salt means the server should return those fields.— 仍要权限与白名单。
Caching
- True —
A fresh cached response can avoid an origin request.— p.17。 - False —
Receiving 304 means no request was sent.— 已有条件请求。 - False —
Cache-Control: 360 is the correct max-age syntax.— 应为 max-age=360。(p.17;修正) - False —
no-cache forbids storing a response.— 允许存,复用前验证。 - False —
no-store and no-cache are equivalent.— 不同。 - False —
private means the response is encrypted.— 限制共享缓存,不是加密。 - False —
An ETag directly specifies how many seconds a response is fresh.— 校验器不是有效期。 - False —
ETags must use one specified hashing algorithm.— opaque validator。 - False —
An ETag is the same thing as a resource ID.— 表示版本与资源身份不同。 - False —
Different media representations can always share the same strong ETag.— 要正确区分表示。 - False —
Expires is only valid when max-age is also present.— 可独立存在。 - False —
Expires takes priority over Cache-Control max-age.— 通常相反。 - False —
Date and Last-Modified always represent the same timestamp.— 消息产生与资源修改不同。 - False —
Every no-cache response must also include Pragma: no-cache.— 不是普遍现代要求。 - False —
Every GET response is necessarily cached.— 还看缓存规则和响应。 - False —
Every POST response is absolutely forbidden from being cached by HTTP.— 不能作绝对结论。 - False —
A cached version selected by Accept never needs Vary.— 缓存需区分响应表示。 - False —
A 304 response should include the full updated JSON body.— 304 无正文;变化则正常返回新表示。
5. Exam Quick Reference(考前速查)
REST / Methods
- REST = Representational State Transfer。(p.3)
- Resources + representations;不是 JSON 的同义词。
- Constraints: client-server / layered / stateless / cacheable;uniform interface 补全;code-on-demand 可选。
- Stateless ≠ no database;共享 session store 也仍有 session state。
- Path 用名词;method 表达操作;query 做筛选。
- Safe: GET / HEAD;附带日志不等于违反 safe。
- Idempotent: GET / HEAD / PUT / DELETE 等;不是“响应必须完全一样”。
- POST: 默认不保证幂等;不只可创建。
- PUT: 已知 URI 创建 / 替换;不能实现为每次累加后还称幂等。
- HEAD: 无响应正文。
Version / Representation / Query
- Version:
/v1/ Accept vendor type / X-API-Version。(p.16) - Accept: 想收什么;Content-Type: 当前 body 是什么。(p.18)
- Vary: 区分 Accept / version 等请求头决定的表示。
- Collection:
/users;individual:/users/:id。 - Query: q / limit / start / sort / fields。(p.32)
- start 含义需定义,fields 需白名单。
Caching
- Fresh hit: 可不联网。
- Revalidation: 发条件请求,未变可 304。
max-age=360: 秒;不是Cache-Control: 360。- no-cache: 可存,复用前验证。
- no-store: 不存。
- private: 不进共享缓存,不是加密。
- ETag: 表示版本;If-None-Match 验证。
- Last-Modified: 修改时间;If-Modified-Since 验证。
- Date: 消息产生时间。
- Expires: 绝对新鲜度到期;max-age 通常优先。
- Pragma: 旧兼容,不是必须随 no-cache 响应设置。
- 304: 有请求、无 body;不是“没有联网”。
最可能的代码 / 设计题
- L22: Schema + required / unique + 自定义 validator。
- L22: Model reference → populate → null 判断。
- L22: Joi 校验并使用转换后的返回值。
- L23: 登录验证 → regenerate → session userId → protected route。
- L23: logout destroy + clearCookie;多实例改共享 store。
- L24: method / URI 设计、分页字段查询、ETag 条件 GET。