推荐答案
// www.javascriptcn.com code example
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';
});
router.get('/about', async (ctx) => {
ctx.body = 'About Page';
});
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});本题详细解读
1. 引入 Koa 和 koa-router
首先,我们需要引入 Koa 和 koa-router 模块。Koa 是一个轻量级的 Node.js 框架,而 koa-router 是 Koa 的一个路由中间件,用于处理 HTTP 请求的路由。
const Koa = require('koa');
const Router = require('koa-router');2. 创建 Koa 和 Router 实例
接下来,我们创建一个 Koa 应用实例和一个 Router 实例。
const app = new Koa(); const router = new Router();
3. 定义路由
使用 router.get() 方法定义路由。第一个参数是路由路径,第二个参数是处理该路由的异步函数。在这个函数中,我们可以通过 ctx 对象来访问请求和响应。
router.get('/', async (ctx) => {
ctx.body = 'Hello World';
});
router.get('/about', async (ctx) => {
ctx.body = 'About Page';
});4. 使用路由中间件
将路由中间件添加到 Koa 应用中。router.routes() 方法返回一个中间件函数,用于处理路由。router.allowedMethods() 方法用于处理不支持的 HTTP 方法,返回 405 Method Not Allowed 或 501 Not Implemented。
app.use(router.routes()).use(router.allowedMethods());
5. 启动服务器
最后,启动 Koa 应用并监听 3000 端口。
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});通过以上步骤,我们成功地在 Koa 应用中使用了 koa-router 中间件来处理路由。