中间件
中间件按什么顺序执行,什么时候短路?
- 注册顺序进入, 退出顺序相反(1 进 → 2 进 → Handler → 2 出 → 1 出);
- 短路:
await next()后不返回就继续, 返回Response立即短路; - 异常: 一律交给
app.onError; - 前提:
next()永不抛错, 不用 try/catch; - 必须注册在 Handler 之前,
app.get("*")写前面会吞掉所有请求;
app.use(logger()); // 所有方法与路径
app.use("/posts/*", cors()); // 路径前缀
app.post("/posts/*", basicAuth({ username: "admin", password: "secret" })); // 方法 + 路径
自定义中间件怎么写?
createMiddleware: 来自hono/factory, 只保住c与next的类型;- 带参数: 把参数放外层;
const auth = createMiddleware<{ Variables: { user: { id: string } } }>(async (c, next) => {
if (!c.req.header("Authorization")) return c.json({ ok: false, error: "unauthorized" }, 401);
c.set("user", { id: "1" });
await next();
});
const header = (value: string) =>
createMiddleware(async (c, next) => {
await next();
c.res.headers.set("X-Message", value);
});
app.use(auth, header("hello"));
- 前提: 泛型里声明
Variables后, 下游才有c.var.user; - 链式
.use(): 每次累加; - 分开注册:
app.use(...)不累加; - 按请求构造:
(c, next) => cors({ origin: c.env.CORS_ORIGIN })(c, next); - 无状态中间件: 在顶层构造一次复用;
- 改写响应必须
await next()之后;
中间件的作用域如何划分?
app.use(secureHeaders());
app.use(requestId());
app.use(logger());
app.use(compress());
app.use("/api/*", cors());
app.use("/api/*", timeout(10_000));
app.use("/api/*", bodyLimit({ maxSize: 1024 * 1024 }));
app.use("/api/*", auth);
app.route("/api", apiRoutes);