文章

前端路由

URL 是由几个部分组成:

protocol: // hostname:port / pathname ? query # hash

路由模块需要实现的功能就是 —— 解析 URL 中的 pathname,根据不同的路径将请求分配给相应的模块去处理。

一个简单的路由是一个类,它的方法能够返回不同的拦截切面,这样的类叫做 HTTP 服务中间件(Middleware)。具体实现代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Router类

const url = require("url");
const path = require("path");

/*
@rule:路径规则
@pathname:路径名
*/
function check(rule, pathname) {
  /* 
  解析规则,比如:/test/:course/:lecture
  paraMatched = ['/test/:course/:lecture', ':course', ':lecture']
  */
  const paraMatched = rule.match(/:[^/]+/g);
  const ruleExp = new RegExp(`^${rule.replace(/:[^/]+/g, "([^/]+)")}$`);

  /*
  解析真正的路径,比如:/test/123/abc
  ruleMatched = ['/test/123/abs', '123', 'abs']
  */
  const ruleMatched = pathname.match(ruleExp);

  /*
  将规则和路径拼接为对象:
  ret = {course: 123, lecture: abc}
  */
  if (ruleMatched) {
    const ret = {};
    if (paraMatched) {
      for (let i = 0; i < paraMatched.length; i++) {
        ret[paraMatched[i].slice(1)] = ruleMatched[i + 1];
      }
    }
    return ret;
  }
  return null;
}

/*
@method: GET/POST/PUT/DELETE
@rule: 路径规则,比如:test/:course/:lecture
@aspect: 拦截函数
*/
function route(method, rule, aspect) {
  return async (ctx, next) => {
    const req = ctx.req;
    if (!ctx.url) ctx.url = url.parse(`http://${req.headers.host}${req.url}`);
    const checked = check(rule, ctx.url.pathname); // 根据路径规则解析路径
    if (!ctx.route && (method === "*" || req.method === method) && !!checked) {
      ctx.route = checked;
      await aspect(ctx, next);
    } else {
      // 如果路径与路由规则不匹配,则跳过当前拦截切面,执行下一个拦截切面
      await next();
    }
  };
}

class Router {
  constructor(base = "") {
    this.baseURL = base;
  }

  get(rule, aspect) {
    return route("GET", path.join(this.baseURL, rule), aspect);
  }

  post(rule, aspect) {
    return route("POST", path.join(this.baseURL, rule), aspect);
  }

  put(rule, aspect) {
    return route("PUT", path.join(this.baseURL, rule), aspect);
  }

  delete(rule, aspect) {
    return route("DELETE", path.join(this.baseURL, rule), aspect);
  }

  all(rule, aspect) {
    return route("*", path.join(this.baseURL, rule), aspect);
  }
}

module.exports = Router;

可以这样使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const Server = require("./lib/server");
const Router = require("./lib/middleware/router");

const app = new Server();
const router = new Router();

app.listen({
  port: 9090,
  host: "0.0.0.0",
});

app.use(
  router.all("/test/:course/:lecture", async ({ route, res }, next) => {
    res.setHeader("Content-Type", "application/json");
    res.body = route;
    await next();
  })
);

app.use(
  router.all(".*", async ({ req, res }, next) => {
    res.setHeader("Content-Type", "text/html");
    res.body = "<h1>Hello world</h1>";
    await next();
  })
);
本文由作者按照 CC BY 4.0 进行授权