How does Koa2 handle routing?

How does Koa2 handle routing?

In Koa2, routing can be handled using the koa-router module. Below is a sample code showing how routing is handled in Koa2.

First, the koa-router module needs to be installed. It can be installed using npm:

npm install koa-router

Then, introduce the koa-router module in the code, and create a koa instance and a router instance:

const Koa = require('koa');
const Router = require('koa-router');

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

Next, a router instance can be used to define routes. You can use the router.get(), , router.post()and other methods to define routes for different HTTP request methods. For example, the following code defines a route for a GET request:

router.get('/hello', async (ctx) => {
    
    
  ctx.body = 'Hello World!';
});

In the above example, when the user visits /hellothe path, it will be returned Hello World!as a response.

It is also possible to define routes with parameters. For example, the following code defines a route for a GET request with parameters:

router.get('/users/:id', async (ctx) => {
    
    
  const userId = ctx.params.id;
  // 根据userId获取用户信息的逻辑代码
  ctx.body = `User ID: ${
      
      userId}`;
});

In the above example, when the user accesses /users/123the path, ctx.params.idit will be set to 123, and then the corresponding processing can be performed according to this parameter.

Finally, you need to register the router instance with the koa instance and start the server:

app.use(router.routes());
app.listen(3000, () => {
    
    
  console.log('Server is running on port 3000');
});

In the above code, app.use(router.routes())the router instance is registered with the koa instance so that the routing can take effect. Then, use app.listen()the method to start the server and listen on port 3000.

Through the above steps, you can process routing in Koa2. Different routing and processing logic can be defined according to actual needs.

Guess you like

Origin blog.csdn.net/qq_51447496/article/details/132692110