前言
koa-router同时支持Koa1和Koa2,使用风格和Express相似,使用过Express的强烈推荐。
示例
- app.js
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())
app.use(router.routes()).use(router.allowedMethods());
app.listen(3000);
- home.js
const Router = require('koa-router');
const home = new Router();
// /home
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.
附录
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(); // set whatever the user returns from their function
} 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(); // set whatever the user returns from their function
} else {
notAllowedThrowable = new HttpError.MethodNotAllowed();
}
throw notAllowedThrowable;
} else {
ctx.status = 405;
ctx.set('Allow', allowedArr.join(', '));
}
}
}
}
});
};
};
使用postman做一下比较
-
成功返回时
-
404时