添加路由(处理不同的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
:
npm install koa-router -D
API 介绍
const Router = require('koa-router');
const router = new