• Koa路由中间件之koa-router


    前言

    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时

  • 相关阅读:
    WebApi 安全认证
    Autofac 学习
    autofac实现批量注入
    Autofac -入门练习
    Struts2 Namespace_命名空间
    Deployment failure on Tomcat 6.x. Could not copy all resources
    chm 已取消到该网页的导航 或者 无法显示网页 的问题
    GPT 分区详解
    mount 中文手册
    rpm 中文手册
  • 原文地址:https://www.cnblogs.com/xpengp/p/12793876.html
Copyright © 2020-2023  润新知