Koa2项目实战2(路由管理、项目结构优化)

添加路由(处理不同的URL请求)

路由:根据不同的URL,调用对应的处理函数。

每一个接口服务,最核心的功能是:根据不同的URL请求,返回不同的数据。也就是调用不同的接口返回不同的数据。

在 Node.js 中使用 Koa 框架添加路由可以通过以下几种方式实现:

第1种:使用原生的 app.use 和条件判断

// 导入koa, koa是一个类
const Koa = require('koa')

const {
   
    APP_PORT } = require('./config/config.env')

// 创建koa实例对象:app
const app = new Koa()

// 使用 app.use() 方法添加中间件,且只能写一个中间件
app.use((ctx, next) => {
   
   
  // 中间件逻辑
  if (ctx.url === '/home') {
   
   
    ctx.body = 'This is the home page';
  } else if (ctx.url === '/about') {
   
   
    ctx.body = 'This is the about page';
  } else {
   
   
    ctx.body = 'Page not found';
  }
});

// 指定端口号并启动服务器
app.listen(APP_PORT, () => {
   
   
  console.log(`server is running on http://localhost:${
     
     APP_PORT}`)
})

第2种:使用第三方路由模块,如 koa-router(常用)

koa-router API

安装koa-router

npm install koa-router -D

API 介绍

const Router = require('koa-router');
const router = new 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值