添加路由

    在 Koa 框架中,路由是指基于 URL 和 HTTP 方法的请求处理器。Koa 本身不内置路由功能,但可以通过使用第三方库如 koa-router 来实现路由功能。


    步骤 1:安装 koa-router

    首先,你需要安装 koa-router

    1pnpm add koa-router

    步骤 2:创建路由文件

    创建一个路由文件,例如 router/index.js

    1const Router = require("koa-router")
    2
    3const router = new Router()
    4
    5// 定义路由
    6router.get("/", async (ctx, next) => {
    7	ctx.body = "Hello, Koa!"
    8})
    9
    10router.get("/users/:id", async (ctx, next) => {
    11	const { id } = ctx.params
    12	ctx.body = `User ${id}`
    13})
    14
    15// 导出路由
    16module.exports = router

    步骤 3:在 Koa 应用中使用路由

    在你的 Koa 应用入口文件中,引入并使用路由:

    1const { APP_PORT } = require("./env/index.js")
    2const Koa = require("koa")
    3const router = require("./router.index.js") // [!code focus]
    4
    5const app = new Koa()
    6
    7// 使用路由中间件
    8app.use(router.routes()).use(router.allowedMethods()) // [!code focus]
    9
    10app.listen(APP_PORT, () => {
    11	console.log(`Server running on http://localhost:${APP_PORT}`)
    12})

    通过这些步骤,你可以在 Koa 应用中配置和使用路由,从而定义不同的端点来处理不同的请求。这使得你的应用能够根据请求的 URL 和 HTTP 方法来执行相应的逻辑。