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

运行原生 HTTP 路由、URL 解析、依赖注入路由与 Express 模式回环实验

JAVASCRIPTWindows x64、Node.js v24.22.3 本地运行环境。explore-router.mjs
explore-router.mjs241 行
import http from 'node:http';
import querystring from 'node:querystring';

function makeCase(name, expected, actual) {
  return {
    name,
    passed: JSON.stringify(expected) === JSON.stringify(actual),
    expected,
    actual,
  };
}

// Case 1: basic http module URL + method routing
async function testHttpBasicRouting() {
  const server = http.createServer((req, res) => {
    const { url, method } = req;
    if (url === '/' && method === 'GET') {
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end('Home Page');
    } else if (url === '/about' && method === 'GET') {
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end('About Page');
    } else {
      res.writeHead(404, { 'Content-Type': 'text/plain' });
      res.end('404 Not Found');
    }
  });

  await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
  const { port } = server.address();
  const base = `http://127.0.0.1:${port}`;
  try {
    const rHome = await fetch(`${base}/`);
    const rAbout = await fetch(`${base}/about`);
    const rPostAbout = await fetch(`${base}/about`, { method: 'POST' });
    const rMissing = await fetch(`${base}/missing`);

    const expected = {
      home: [200, 'Home Page'],
      about: [200, 'About Page'],
      postAbout: [404, '404 Not Found'],
      missing: [404, '404 Not Found'],
    };
    const actual = {
      home: [rHome.status, await rHome.text()],
      about: [rAbout.status, await rAbout.text()],
      postAbout: [rPostAbout.status, await rPostAbout.text()],
      missing: [rMissing.status, await rMissing.text()],
    };
    return makeCase('http_basic_routing', expected, actual);
  } finally {
    await new Promise((resolve) => server.close(resolve));
  }
}

// Case 2: URL constructor and querystring parsing
function testUrlAndQueryParsing() {
  const myUrl = new URL('http://localhost:8888/start?foo=bar&hello=world');
  const qsParsed = querystring.parse('foo=bar&hello=world');

  const expected = {
    pathname: '/start',
    foo: 'bar',
    hello: 'world',
    qsFoo: 'bar',
    qsHello: 'world',
  };
  const actual = {
    pathname: myUrl.pathname,
    foo: myUrl.searchParams.get('foo'),
    hello: myUrl.searchParams.get('hello'),
    qsFoo: qsParsed.foo,
    qsHello: qsParsed.hello,
  };
  return makeCase('url_and_query_parsing', expected, actual);
}

// Case 3: dependency-injected router module (server.start(router.route))
async function testDiRouterArchitecture() {
  const routedPaths = [];
  function route(pathname) {
    routedPaths.push(pathname);
    if (pathname === '/start') return 'Handled /start';
    if (pathname === '/upload') return 'Handled /upload';
    return 'Hello World';
  }

  function start(routeFn) {
    function onRequest(request, response) {
      const pathname = new URL(request.url, `http://${request.headers.host}`).pathname;
      const body = routeFn(pathname);
      response.writeHead(200, { 'Content-Type': 'text/plain' });
      response.end(body);
    }
    return http.createServer(onRequest);
  }

  const server = start(route);
  await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
  const { port } = server.address();
  const base = `http://127.0.0.1:${port}`;
  try {
    const rRoot = await (await fetch(`${base}/`)).text();
    const rStart = await (await fetch(`${base}/start?foo=bar`)).text();
    const rUpload = await (await fetch(`${base}/upload`)).text();

    const expected = {
      routedPaths: ['/', '/start', '/upload'],
      responses: ['Hello World', 'Handled /start', 'Handled /upload'],
    };
    const actual = {
      routedPaths,
      responses: [rRoot, rStart, rUpload],
    };
    return makeCase('di_router_architecture', expected, actual);
  } finally {
    await new Promise((resolve) => server.close(resolve));
  }
}

// Case 4: Express-style routing patterns (params, query, router prefix, auth, priority, error handler)
async function testExpressStyleRouterPatterns() {
  const logs = [];

  function matchPattern(pattern, pathname) {
    const pSegs = pattern.split('/').filter(Boolean);
    const uSegs = pathname.split('/').filter(Boolean);
    if (pSegs.length !== uSegs.length) return null;
    const params = {};
    for (let i = 0; i < pSegs.length; i += 1) {
      if (pSegs[i].startsWith(':')) {
        params[pSegs[i].slice(1)] = decodeURIComponent(uSegs[i]);
      } else if (pSegs[i] !== uSegs[i]) {
        return null;
      }
    }
    return params;
  }

  const routes = [
    { method: 'GET', pattern: '/', handler: () => ({ status: 200, body: 'Hello, World!' }) },
    { method: 'POST', pattern: '/submit', handler: () => ({ status: 200, body: 'Form submitted!' }) },
    { method: 'GET', pattern: '/users', handler: () => ({ status: 200, body: 'List of users' }) },
    { method: 'GET', pattern: '/users/me', handler: () => ({ status: 200, body: 'Current user (priority)' }) },
    { method: 'GET', pattern: '/users/:id', handler: (req) => ({ status: 200, body: `User ID: ${req.params.id}` }) },
    { method: 'GET', pattern: '/search', handler: (req) => ({ status: 200, body: `Search query: ${req.query.q}` }) },
    {
      method: 'GET',
      pattern: '/admin',
      auth: true,
      handler: () => ({ status: 200, body: 'Admin page' }),
    },
    {
      method: 'GET',
      pattern: '/boom',
      handler: () => {
        throw new Error('Synthetic route failure');
      },
    },
  ];

  const server = http.createServer((req, res) => {
    const parsed = new URL(req.url, `http://${req.headers.host}`);
    logs.push(`${req.method} ${parsed.pathname}`);
    try {
      for (const r of routes) {
        if (r.method !== req.method) continue;
        const params = matchPattern(r.pattern, parsed.pathname);
        if (params !== null) {
          if (r.auth && !req.headers.authorization) {
            res.writeHead(401, { 'Content-Type': 'text/plain' });
            res.end('Unauthorized');
            return;
          }
          const result = r.handler({
            params,
            query: Object.fromEntries(parsed.searchParams),
          });
          res.writeHead(result.status, { 'Content-Type': 'text/plain' });
          res.end(result.body);
          return;
        }
      }
      res.writeHead(404, { 'Content-Type': 'text/plain' });
      res.end('Not Found');
    } catch {
      res.writeHead(500, { 'Content-Type': 'text/plain' });
      res.end('Something broke!');
    }
  });

  await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
  const { port } = server.address();
  const base = `http://127.0.0.1:${port}`;
  try {
    const rPost = await fetch(`${base}/submit`, { method: 'POST' });
    const rUsers = await fetch(`${base}/users`);
    const rPriority = await fetch(`${base}/users/me`);
    const rDynamic = await fetch(`${base}/users/42`);
    const rQuery = await fetch(`${base}/search?q=nodejs`);
    const rNoAuth = await fetch(`${base}/admin`);
    const rWithAuth = await fetch(`${base}/admin`, { headers: { Authorization: 'Bearer ok' } });
    const rErr = await fetch(`${base}/boom`);

    const expected = {
      post: [200, 'Form submitted!'],
      usersGroup: [200, 'List of users'],
      priority: [200, 'Current user (priority)'],
      dynamicParam: [200, 'User ID: 42'],
      queryParam: [200, 'Search query: nodejs'],
      adminDenied: [401, 'Unauthorized'],
      adminAllowed: [200, 'Admin page'],
      errorHandler: [500, 'Something broke!'],
      loggedCount: 8,
    };
    const actual = {
      post: [rPost.status, await rPost.text()],
      usersGroup: [rUsers.status, await rUsers.text()],
      priority: [rPriority.status, await rPriority.text()],
      dynamicParam: [rDynamic.status, await rDynamic.text()],
      queryParam: [rQuery.status, await rQuery.text()],
      adminDenied: [rNoAuth.status, await rNoAuth.text()],
      adminAllowed: [rWithAuth.status, await rWithAuth.text()],
      errorHandler: [rErr.status, await rErr.text()],
      loggedCount: logs.length,
    };
    return makeCase('express_style_router_patterns', expected, actual);
  } finally {
    await new Promise((resolve) => server.close(resolve));
  }
}

const cases = [
  await testHttpBasicRouting(),
  testUrlAndQueryParsing(),
  await testDiRouterArchitecture(),
  await testExpressStyleRouterPatterns(),
];

console.log(JSON.stringify({ version: process.version, cases }));
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

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

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

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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