路由(Routing)是由一个 URI(或者叫路径)和一个特定的 HTTP 方法(GET、POST 等) 组成的,涉及到应用如何响应客户端对某个网站节点的访问。

通俗的讲:路由就是根据不同的 URL 地址,加载不同的页面实现不同的功能。

Koa 中的路由和 Express 有所不同,在 Express 中直接引入 Express 就可以配置路由,但是在 Koa 中我们需要安装对应的 koa-router 路由模块来实现。

npm install koa-router --save
复制代码

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

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

router.get('/',async (ctx) => {
ctx.body = "hello koa"
})

router.get('/news',async (ctx) => {
ctx.type = 'html';
ctx.body = '<h2>新闻列表</h2>';
})

// 调用router.routes()来组装匹配好的路由,返回一个合并好的中间件
app.use(router.routes());
/*
调用router.allowedMethods()获得一个中间件,当发送了不符合的请求时,
会返回 `405 Method Not Allowed` 或 `501 Not Implemented`
*/
app.use(router.allowedMethods({
// throw: true, // 抛出错误,代替设置响应头状态
// notImplemented: () => '不支持当前请求所需要的功能',
// methodNotAllowed: () => '不支持的请求方式'
}));

app.listen(3000,()=>{
console.log('应用已经启动,http://localhost:3000');
});
复制代码

2. Koa 路由 get 传值

在 koa2 中 GET 传值通过 request 接收,但是接收的方法有两种:query 和 querystring。

query:返回的是格式化好的参数对象。

querystring:返回的是请求字符串。

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

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

// http://localhost:3000/newsContent?id=123&name=sport
router.get('/newsContent',async (ctx) => {
/**
* 从ctx中读取get传值
*/
console.log(ctx.query); // { id: '123', name: 'sport' } 推荐
console.log(ctx.querystring); // id=123&name=sport
console.log(ctx.url); // /newsContent?id=123&name=sport
/**
* 从ctx中读取get传值
*/
console.log(ctx.request.query); // { id: '123', name: 'sport' }
console.log(ctx.request.querystring); // id=123&name=sport
console.log(ctx.request.url); // /newsContent?id=123&name=sport

ctx.body="新闻详情"
})


app.use(router.routes());
app.use(router.allowedMethods());

app.listen(3000,()=>{
console.log('应用已经启动,http://localhost:3000');
});
复制代码

3. Koa 动态路由

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

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

// http://localhost:3000/newsContent/123
router.get('/newsContent/:id',async (ctx) => {
// 获取动态路由传入的值
console.log(ctx.params); // { id: '123' }
ctx.body="新闻详情"
})

/*
动态路由里可传入多个值
*/
// http://localhost:3000/newsDetail/123/456
router.get('/newsDetail/:id/:aid',async (ctx) => {
console.log(ctx.params); // { id: '123', aid: '456' }
ctx.body="新闻具体"
})

app.use(router.routes());
app.use(router.allowedMethods());

app.listen(3000,()=>{
console.log('应用已经启动,http://localhost:3000');
});