蓝色天空.知识 · 实践 · 创造
我的收藏
Node.js 教程目录 38章
Node.js / LEARN BY DOING

Node.js Express 框架

核对 Express 中间件管道、Request/Response 常用属性与方法、通配路由、静态资源托管、GET/POST 表单解析、multipart 文件上传与 Cookie 管理的离线契约实测。

学完这一章,你能够

  • 核对 Express 中间件管道、Request/Response 常用属性与方法、通配路由、静态资源托管、GET/POST 表单解析、multipart 文件上传与 Cookie 管理的离线契约实测。

Express 核心特性与配套中间件

Express 是 Node.js 生态中简洁灵活的 Web 应用框架,基于原生 `http` 模块封装了完整的 HTTP 工具链,便于快速构建站点与接口服务。其三大核心特性为:通过可组合的中间件链顺序响应和处理 HTTP 请求、使用路由表将不同 HTTP 方法与路径分发到对应处理器、以及通过向模板引擎传参动态渲染 HTML 页面。

在独立项目中安装 Express 后会写入 `node_modules/express`(现代 npm 默认自动记录依赖,无需再手动加 `--save`),并可通过 `npm list express` 查看已装版本。配套常用中间件包括:`body-parser`(解析 JSON、Raw、Text 与 `application/x-www-form-urlencoded` 请求体;Express 4.16+ 已内置 `express.json()` 与 `express.urlencoded()`)、`cookie-parser`(把请求头中的 Cookie 解析为 `req.cookies` 对象)以及 `multer`(专门处理 `enctype="multipart/form-data"` 文件上传表单)。

最小应用实例与 Request/Response 常用成员

创建 Express 应用的基本步骤为调用工厂函数生成 `app` 实例、注册 `app.get('/', handler)` 返回 `Hello World` 并调用 `app.listen(port, cb)` 启动监听,可通过 `server.address()` 读取监听地址与端口。原页浏览器访问结果截图未缓存,已保留锚点。

路由回调接收 `req`(Request)与 `res`(Response)两个对象。`req` 封装了客户端请求的全部上下文,核心属性与方法包括:`req.app`(访问所属 Express 实例)、`req.baseUrl`(路由挂载路径)、`req.body` 与 `req.cookies`(解析后的请求体与 Cookie)、`req.fresh` / `req.stale`(缓存新鲜度判定)、`req.hostname` / `req.ip`、`req.originalUrl`(原始完整 URL)、`req.params`(命名路径参数)、`req.path`(纯路径)、`req.protocol`、`req.query`(查询参数对象)、`req.route`、`req.subdomains`,以及内容协商与头部读取方法 `req.accepts()`、`req.acceptsCharsets` / `req.acceptsEncodings` / `req.acceptsLanguages`、`req.get()` 与 `req.is()`。

`res` 对象负责构造并发送 HTTP 响应,核心成员包括:`res.app`、`res.append()`(向同名响应头追加值,注意之后再调用 `res.set()` 会重置先前值)、`res.cookie(name, value, option)`(支持 `domain`、`expires`、`httpOnly`、`maxAge`、`path`、`secure`、`signed` 选项)与 `res.clearCookie()`、`res.download()`、`res.get()`、`res.json()` 与 `res.jsonp()`、`res.location()`(仅设 `Location` 头不设状态码或结束响应)与 `res.redirect()`(默认 302 跳转)、`res.render(view, locals, callback)`(渲染视图模板,异常时自动调用 `next(err)`)、`res.send()`、`res.sendFile()`(按扩展名自动设置 `Content-Type`)、`res.set()`、`res.status()` 以及 `res.type()`。

路由分发与静态文件托管

路由决定由哪个处理器响应特定 HTTP 方法与路径组合。典型路由配置同时区分 `GET /`、`POST /`、`/list_user`、`/del_user` 以及通配路径 `/ab*cd`(可匹配 `/abcd`、`/ab123cd`,但不匹配 `/abcdefg`)。本站使用零外部依赖的本地迷你 Express 契约服务在 Node.js v24.22.3 实测:`GET /` 返回 `Hello GET`、`POST /` 返回 `Hello POST`、`/list_user` 返回 `用户列表页面`、`/del_user` 返回 `删除页面`、`/ab123cd` 命中通配路由返回 `正则匹配`,而 `/abcdefg` 返回 `404`。原页 3 张路由访问截图未缓存,已保留锚点。

静态图片、CSS 与前端脚本可通过内置中间件 `express.static('public')` 挂载到 `/public` 虚拟前缀统一托管,避免为每个资源单独写路由。本站实测挂载 `/public` 静态中间件后,请求 `/public/assets/badge.svg` 返回状态码 `200`、`Content-Type: image/svg+xml` 与 `69` 字节 SVG 内容,同时防止越界访问目录之外的文件。原页静态图片访问截图未缓存,已保留锚点。

GET/POST 表单提交、文件上传与 Cookie 管理

表单采用 `method="GET"` 提交时,输入字段会拼在 URL 查询串中,服务端由 `req.query` 提取并序列化为 JSON 返回。本站实测请求 `/process_get?first_name=Lin&last_name=Chen`,服务端解析出 `{"first_name":"Lin","last_name":"Chen"}` 并准确回传。原页 2 张 GET 表单演示图未缓存,已保留锚点。

表单改用 `method="POST"` 提交时,字段放在请求体中以 `application/x-www-form-urlencoded` 编码传输,服务端需先挂载 `urlencoded` 解析中间件再从 `req.body` 读取。本站实测向 `/process_post` 发送 `first_name=Ada&last_name=Lovelace`,中间件解析后返回 `{"first_name":"Ada","last_name":"Lovelace"}`。原页 2 张 POST 表单演示图未缓存,已保留锚点。

文件上传表单必须设置 `method="post"` 且 `enctype="multipart/form-data"`,服务端通过 `multer` 等多段表单解析器提取临时文件信息(如 `originalname`、`path`)并转存到目标目录(工程上务必使用 `path.basename` 过滤原始文件名防止路径穿越)。本站实测向 `/file_upload` 上传 `12` 字节文本文件 `sample.txt`,接口返回 `{"message":"File uploaded successfully","filename":"sample.txt","bytes":12}` 且落盘内容与 `hello upload` 完全一致。原页 2 张上传演示图未缓存,已保留锚点。

Cookie 管理依赖中间件解析请求头 `Cookie` 字段为键值对象 `req.cookies`,响应端则通过 `res.cookie()` 下发 `Set-Cookie` 头。本站实测发送 `Cookie: theme=dark; lang=zh-CN` 至 `/cookies`,服务端准确解析出 `{"theme":"dark","lang":"zh-CN"}`,同时 `res.cookie('session', 'ok', { path: '/', httpOnly: true })` 输出 `session=ok; Path=/; HttpOnly`,连续两次 `res.append('X-Trace', ...)` 合并输出 `step1, step2`。进一步查阅完整 API 可参考 Express 官方 4.x/5.x 文档。原页终端动图未缓存,已保留锚点。

运行离线 Express 契约中间件、通配路由、静态服务、表单上传与 Cookie 实验

含完整源码 · 349 行
展开查看收起
javascript
import http from 'node:http';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';

function parseCookies(header = '') {
  const out = {};
  for (const part of header.split(';')) {
    const idx = part.indexOf('=');
    if (idx > 0) {
      const k = part.slice(0, idx).trim();
      const v = decodeURIComponent(part.slice(idx + 1).trim());
      out[k] = v;
    }
  }
  return out;
}

function parseMultipart(buffer, contentType) {
  const m = contentType.match(/boundary=(?:"([^"]+)"|([^;\s]+))/i);
  if (!m) return [];
  const boundary = `--${m[1] || m[2]}`;
  const raw = buffer.toString('latin1');
  const parts = raw.split(boundary).slice(1, -1);
  const files = [];
  for (const part of parts) {
    const trimmed = part.startsWith('\r\n') ? part.slice(2) : part;
    const sepIdx = trimmed.indexOf('\r\n\r\n');
    if (sepIdx === -1) continue;
    const headerBlock = trimmed.slice(0, sepIdx);
    let bodyStr = trimmed.slice(sepIdx + 4);
    if (bodyStr.endsWith('\r\n')) bodyStr = bodyStr.slice(0, -2);
    const nameMatch = headerBlock.match(/name="([^"]+)"/);
    const fileMatch = headerBlock.match(/filename="([^"]+)"/);
    if (fileMatch) {
      files.push({
        fieldname: nameMatch ? nameMatch[1] : 'file',
        originalname: fileMatch[1],
        data: Buffer.from(bodyStr, 'latin1'),
      });
    }
  }
  return files;
}

function createMiniExpress() {
  const middlewares = [];
  const routes = [];

  function compilePattern(pattern) {
    const escaped = pattern
      .replace(/[.+?^${}()|[\]\\]/g, '\\$&')
      .replace(/\*/g, '.*');
    return new RegExp(`^${escaped}$`);
  }

  const app = {
    use(prefixOrFn, maybeFn) {
      if (typeof prefixOrFn === 'function') {
        middlewares.push({ prefix: '', fn: prefixOrFn });
      } else {
        middlewares.push({ prefix: prefixOrFn, fn: maybeFn });
      }
    },
    get(pattern, handler) {
      routes.push({ method: 'GET', pattern, regex: compilePattern(pattern), handler });
    },
    post(pattern, handler) {
      routes.push({ method: 'POST', pattern, regex: compilePattern(pattern), handler });
    },
    listen(port, host) {
      const server = http.createServer(async (req, res) => {
        const parsed = new URL(req.url || '/', 'http://127.0.0.1');
        req.path = parsed.pathname;
        req.originalUrl = req.url || '/';
        req.query = Object.fromEntries(parsed.searchParams.entries());
        req.cookies = {};
        req.body = {};
        req.files = [];
        req.get = (name) => req.headers[name.toLowerCase()];

        const chunks = [];
        for await (const chunk of req) chunks.push(chunk);
        req.rawBody = Buffer.concat(chunks);

        res.status = (code) => {
          res.statusCode = code;
          return res;
        };
        res.set = (k, v) => {
          res.setHeader(k, v);
          return res;
        };
        res.append = (k, v) => {
          const prev = res.getHeader(k);
          if (!prev) res.setHeader(k, v);
          else res.setHeader(k, Array.isArray(prev) ? [...prev, v] : [prev, v]);
          return res;
        };
        res.cookie = (name, val, opts = {}) => {
          const segs = [`${name}=${encodeURIComponent(val)}`];
          if (opts.path) segs.push(`Path=${opts.path}`);
          if (opts.httpOnly) segs.push('HttpOnly');
          res.append('Set-Cookie', segs.join('; '));
          return res;
        };
        res.json = (obj) => {
          res.setHeader('Content-Type', 'application/json; charset=utf-8');
          res.end(JSON.stringify(obj));
        };
        res.send = (val) => {
          if (typeof val === 'object' && val !== null) return res.json(val);
          res.setHeader('Content-Type', 'text/plain; charset=utf-8');
          res.end(String(val));
        };

        let stopped = false;
        for (const mw of middlewares) {
          if (mw.prefix && !req.path.startsWith(mw.prefix)) continue;
          let calledNext = false;
          await mw.fn(req, res, () => {
            calledNext = true;
          });
          if (!calledNext || res.writableEnded) {
            stopped = true;
            break;
          }
        }
        if (stopped) return;

        const matched = routes.find((r) => r.method === req.method && r.regex.test(req.path));
        if (!matched) {
          res.status(404).send('Not Found');
          return;
        }
        await matched.handler(req, res);
      });
      return new Promise((resolve) => server.listen(port, host, () => resolve(server)));
    },
  };
  return app;
}

async function main() {
  const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'mbsky-express-'));
  const pubDir = path.join(tmpDir, 'public', 'assets');
  const uploadDir = path.join(tmpDir, 'uploads');
  await fs.mkdir(pubDir, { recursive: true });
  await fs.mkdir(uploadDir, { recursive: true });
  const svgContent = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"></svg>';
  await fs.writeFile(path.join(pubDir, 'badge.svg'), svgContent, 'utf8');

  const app = createMiniExpress();

  // Cookie parser middleware
  app.use((req, _res, next) => {
    req.cookies = parseCookies(req.headers.cookie || '');
    next();
  });

  // URL-encoded & multipart parser middleware
  app.use((req, _res, next) => {
    const ct = req.headers['content-type'] || '';
    if (ct.includes('application/x-www-form-urlencoded')) {
      req.body = Object.fromEntries(new URLSearchParams(req.rawBody.toString('utf8')).entries());
    } else if (ct.includes('multipart/form-data')) {
      req.files = parseMultipart(req.rawBody, ct);
    }
    next();
  });

  // Static middleware mounted at /public
  app.use('/public', async (req, res, next) => {
    const rel = req.path.slice('/public'.length).replace(/^\/+/, '');
    const target = path.resolve(path.join(tmpDir, 'public'), rel);
    if (!target.startsWith(path.resolve(path.join(tmpDir, 'public')) + path.sep)) {
      res.status(403).send('Forbidden');
      return;
    }
    try {
      const data = await fs.readFile(target);
      const mime = target.endsWith('.svg') ? 'image/svg+xml' : 'application/octet-stream';
      res.set('Content-Type', mime);
      res.end(data);
    } catch {
      next();
    }
  });

  app.get('/', (_req, res) => res.send('Hello GET'));
  app.post('/', (_req, res) => res.send('Hello POST'));
  app.get('/list_user', (_req, res) => res.send('用户列表页面'));
  app.get('/del_user', (_req, res) => res.send('删除页面'));
  app.get('/ab*cd', (_req, res) => res.send('正则匹配'));
  app.get('/process_get', (req, res) => {
    res.json({ first_name: req.query.first_name, last_name: req.query.last_name });
  });
  app.post('/process_post', (req, res) => {
    res.json({ first_name: req.body.first_name, last_name: req.body.last_name });
  });
  app.post('/file_upload', async (req, res) => {
    const file = req.files[0];
    const dest = path.join(uploadDir, path.basename(file.originalname));
    await fs.writeFile(dest, file.data);
    res.json({
      message: 'File uploaded successfully',
      filename: file.originalname,
      bytes: file.data.length,
    });
  });
  app.get('/cookies', (req, res) => {
    res.append('X-Trace', 'step1');
    res.append('X-Trace', 'step2');
    res.cookie('session', 'ok', { path: '/', httpOnly: true });
    res.json({ cookies: req.cookies });
  });

  const server = await app.listen(0, '127.0.0.1');
  const { port } = server.address();
  const base = `http://127.0.0.1:${port}`;
  const cases = [];

  try {
    // Case 1: routing_and_wildcard_matching
    const rGet = await (await fetch(`${base}/`)).text();
    const rPost = await (await fetch(`${base}/`, { method: 'POST' })).text();
    const rList = await (await fetch(`${base}/list_user`)).text();
    const rDel = await (await fetch(`${base}/del_user`)).text();
    const rWild = await (await fetch(`${base}/ab123cd`)).text();
    const rMiss = await fetch(`${base}/abcdefg`);
    const actual1 = {
      rootGet: rGet,
      rootPost: rPost,
      listUser: rList,
      delUser: rDel,
      wildcard: rWild,
      missStatus: rMiss.status,
    };
    const expected1 = {
      rootGet: 'Hello GET',
      rootPost: 'Hello POST',
      listUser: '用户列表页面',
      delUser: '删除页面',
      wildcard: '正则匹配',
      missStatus: 404,
    };
    cases.push({
      name: 'routing_and_wildcard_matching',
      passed: JSON.stringify(actual1) === JSON.stringify(expected1),
      expected: expected1,
      actual: actual1,
    });

    // Case 2: static_middleware_and_get_query
    const staticRes = await fetch(`${base}/public/assets/badge.svg`);
    const staticBody = await staticRes.text();
    const getRes = await fetch(`${base}/process_get?first_name=Lin&last_name=Chen`);
    const getJson = await getRes.json();
    const actual2 = {
      staticStatus: staticRes.status,
      staticType: staticRes.headers.get('content-type'),
      staticBytes: Buffer.byteLength(staticBody, 'utf8'),
      queryJson: getJson,
    };
    const expected2 = {
      staticStatus: 200,
      staticType: 'image/svg+xml',
      staticBytes: Buffer.byteLength(svgContent, 'utf8'),
      queryJson: { first_name: 'Lin', last_name: 'Chen' },
    };
    cases.push({
      name: 'static_middleware_and_get_query',
      passed: JSON.stringify(actual2) === JSON.stringify(expected2),
      expected: expected2,
      actual: actual2,
    });

    // Case 3: post_urlencoded_and_multipart_upload
    const postRes = await fetch(`${base}/process_post`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: 'first_name=Ada&last_name=Lovelace',
    });
    const postJson = await postRes.json();

    const boundary = '----BlueSkyBoundary7MA4YWxkTrZu0gW';
    const mpBody = [
      `--${boundary}`,
      'Content-Disposition: form-data; name="image"; filename="sample.txt"',
      'Content-Type: text/plain',
      '',
      'hello upload',
      `--${boundary}--`,
      '',
    ].join('\r\n');
    const upRes = await fetch(`${base}/file_upload`, {
      method: 'POST',
      headers: { 'Content-Type': `multipart/form-data; boundary=${boundary}` },
      body: mpBody,
    });
    const upJson = await upRes.json();
    const savedText = await fs.readFile(path.join(uploadDir, 'sample.txt'), 'utf8');
    const actual3 = { postJson, uploadJson: upJson, savedText };
    const expected3 = {
      postJson: { first_name: 'Ada', last_name: 'Lovelace' },
      uploadJson: { message: 'File uploaded successfully', filename: 'sample.txt', bytes: 12 },
      savedText: 'hello upload',
    };
    cases.push({
      name: 'post_urlencoded_and_multipart_upload',
      passed: JSON.stringify(actual3) === JSON.stringify(expected3),
      expected: expected3,
      actual: actual3,
    });

    // Case 4: cookie_parser_and_response_headers
    const cookieRes = await fetch(`${base}/cookies`, {
      headers: { Cookie: 'theme=dark; lang=zh-CN' },
    });
    const cookieJson = await cookieRes.json();
    const actual4 = {
      parsedCookies: cookieJson.cookies,
      setCookie: cookieRes.headers.get('set-cookie'),
      traceHeader: cookieRes.headers.get('x-trace'),
    };
    const expected4 = {
      parsedCookies: { theme: 'dark', lang: 'zh-CN' },
      setCookie: 'session=ok; Path=/; HttpOnly',
      traceHeader: 'step1, step2',
    };
    cases.push({
      name: 'cookie_parser_and_response_headers',
      passed: JSON.stringify(actual4) === JSON.stringify(expected4),
      expected: expected4,
      actual: actual4,
    });
  } finally {
    await new Promise((resolve) => server.close(resolve));
    await fs.rm(tmpDir, { recursive: true, force: true });
  }

  console.log(JSON.stringify({ version: process.version, cases }));
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
核对 GET/POST/通配路由与 404 分发、/public 静态文件 200 返回、GET 查询参数与 POST urlencoded/multipart 上传落盘,以及 Cookie 解析与 Set-Cookie/append 响应头行为。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1041.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Node.js

课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a1041.zip

下载课程关联工程包:Node.js

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1049.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

`GET` 表单参数通过 URL 查询串传递,直接从 `req.query` 读取;`POST` 普通表单默认采用 `application/x-www-form-urlencoded`,经 `express.urlencoded()` / `body-parser` 解析后从 `req.body` 读取;文件上传需设置 `enctype="multipart/form-data"`,经 `multer` 等多段解析中间件处理后从 `req.file` 或 `req.files` 读取。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习