前言
koa-router同时支持Koa1和Koa2,使用风格和Express相似,使用过Express的强烈推荐。
示例
app.js
1 2 3 4 5 6 7 8 9 10 11
| const Koa = require('koa'); const app = new Koa(); const Router = require('koa-router'); const router = new Router();
router.use('/home', ...require('./home'));
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000);
|
home.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const Router = require('koa-router'); const home = new Router();
home.get('/', async (ctx, next) => { ctx.response.status = 200; ctx.response.body = 'home'; await next() }); home.post('/list', async (ctx, next) => { ctx.response.status = 200; ctx.response.body = 'home-list'; await next() });
module.exports = [home.routes(), home.allowedMethods()];
|
router.allowedMethods()实现了什么?
- 其实查看一下源码就会发现,allowedMethods方法只是在ctx.status为404时,为响应头设置status和Allow而已。不添加也没有问题,返回404 Not Find.
附录
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| Router.prototype.allowedMethods = function (options) { options = options || {}; var implemented = this.methods;
return function allowedMethods(ctx, next) { return next().then(function() { var allowed = {};
if (!ctx.status || ctx.status === 404) { for (var i = 0; i < ctx.matched.length; i++) { var route = ctx.matched[i]; for (var j = 0; j < route.methods.length; j++) { var method = route.methods[j]; allowed[method] = method } }
var allowedArr = Object.keys(allowed);
if (!~implemented.indexOf(ctx.method)) { if (options.throw) { var notImplementedThrowable; if (typeof options.notImplemented === 'function') { notImplementedThrowable = options.notImplemented(); } else { notImplementedThrowable = new HttpError.NotImplemented(); } throw notImplementedThrowable; } else { ctx.status = 501; ctx.set('Allow', allowedArr.join(', ')); } } else if (allowedArr.length) { if (ctx.method === 'OPTIONS') { ctx.status = 200; ctx.body = ''; ctx.set('Allow', allowedArr.join(', ')); } else if (!allowed[ctx.method]) { if (options.throw) { var notAllowedThrowable; if (typeof options.methodNotAllowed === 'function') { notAllowedThrowable = options.methodNotAllowed(); } else { notAllowedThrowable = new HttpError.MethodNotAllowed(); } throw notAllowedThrowable; } else { ctx.status = 405; ctx.set('Allow', allowedArr.join(', ')); } } } } }); }; };
|
使用postman做一下比较
成功返回时
![](/images/blog/202304/1682260913XjMQM.png)
404时
![](https://img2020.cnblogs.com/blog/1985071/202004/1985071-20200428135958118-153254421.png)