koa-router介绍

来源:互联网 发布:知乎 复制 编辑:程序博客网 时间:2024/06/08 16:29

在springMVC的9个组件中,有一个很重要的组件是handlermapping。这个组件的作用就是url处理器映射。在nodeJs中,负责这部分功能的是一个叫做koa-router的模块。

koa-router用法

首先在package.json配置文件中添加koa-router依赖,然后执行npm install命令加载依赖。

然后在app.js中导入koa-router模块。

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

可以使用router的get或者post方法去接收http请求并调用对应的函数。如router.get('/path',async fn)或者router.post('/path',async fn)。

最后,需要加上下面这句代码将router注册到app对象上面。

app.use(router.routes());
这样,就可以让router替你接管url和处理函数之间的映射,而不需要你关心真实的访问路径如何。

但是,在处理post请求时,koa无法解析http请求体中的数据,这时我们需要引入另外一个模块叫做koa-bodyparser。

引入bodyparser之后需要注册到app对象上,且在router之前注册,然后才可能在router的post请求的处理函数中获取http请求体中的数据。

get请求代码实例:

'use strict';

const Koa = require('koa');

const router = require('koa-router')();
// 创建一个Koa对象表示web app本身:
const app = new Koa();

// 对于任何请求,app将调用该异步函数处理请求:
app.use(async (ctx, next) => {
    console.log(ctx.request.path+':'+ctx.request.method);
    await next();
});

// add url-route:
router.get('/hello/:name', async (ctx, next) => {
    var name = ctx.params.name;
    ctx.response.body = `<h1>Hello, ${name}!</h1>`;
});

router.get('/', async (ctx, next) => {
    ctx.response.body = '<h1>Index</h1>';
});

app.use(router.routes());
// 在端口3000监听:
app.listen(3000);
console.log('app started at port 3000...');

post请求实例除需要引入koa-bodyparser模块之外,其他并无区别。就不贴出代码了。

原创粉丝点击