Hono API
本项目使用 Hono.js 处理 API
Hono 基本用法
ts
import { Hono } from "hono";
import { logger } from "hono/logger";
import { cors } from "hono/cors";
import { healthcheckRouter } from "./healthcheck";
import { blogRouter } from "./blog";
import { categoryRouter } from "./category";
import { tagRouter } from "./tag";
import { logoutRouter } from "./logout";
import { staticsticRouter } from "./statistic";
import { themeRouter } from "./theme";
import { uploadRouter } from "./upload";
import { csrf } from "hono/csrf";
export const app = new Hono().basePath("/api/v1");
// 全局中间件
app.use(logger());
app.use(cors());
app.use(csrf());
// 注册API路由
app.route("/healthcheck", healthcheckRouter);
app.route("/blog", blogRouter);
app.route("/blog/category", categoryRouter);
app.route("/blog/tag", tagRouter);
app.route("/logout", logoutRouter);
app.route("/statistic", staticsticRouter);
app.route("/theme", themeRouter);
app.route("/upload", uploadRouter);
app.notFound((c) => {
return c.json(
{
code: 1,
message: "API endpoint not found",
data: null,
},
404,
);
});
为什么要加 /api/v1
版本号?
ts
import { type RouteConfig, index, route } from "@react-router/dev/routes";
export default [
index("routes/home.tsx"),
route("api/*", "routes/api.tsx"),
route(":lang?/admin", "routes/admin.tsx"),
] satisfies RouteConfig;
// visit -> http://localhost:5173/api/admin
// which route match ?
正确答案:route(":lang?/admin", "routes/admin.tsx")
。
这样我们路由一般不会在前端写 /api/v1
的路由,写的话也可以避开这个路由。