梗概

  • 先配置router对象,然后将配置好的router作为中间件拆入koa

示例

Setting Up Routes

To create routes in a Koa application, you need to use the koa-router module. First, you need to install it using npm:

npm install koa-router

After installing koa-router, you can set up your routes in your Koa application like this:

const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
router.get('/', async (ctx) => {
  ctx.body = 'Hello World';
});
app
  .use(router.routes())
  .use(router.allowedMethods());
app.listen(3000);

In this example, we define a simple route that responds with “Hello World” when a GET request is made to the root URL (/).

Route Parameters

You can also define routes with parameters in Koa. Route parameters are placeholders in the route URL that can capture values from incoming requests. Here’s an example:

router.get('/users/:id', async (ctx) => {
  const userId = ctx.params.id;
  ctx.body = `User ID: ${userId}`;
});

In this example, when a request is made to /users/123, the value 123 will be captured as the id parameter and displayed in the response.