蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

JAVASCRIPTWindows x64、Node.js v24.22.3 本地运行环境。explore-express-framework.mjs
explore-express-framework.mjs349 行
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);
});
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、Node.js v24.22.3 本地运行环境。

入口文件:projects/nodejs-express-framework-lab/explore-express-framework.mjs

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-express-framework.mjs,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、Node.js v24.22.3 本地运行环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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