• koa-router匹配多个路由添加中间件函数


    node服务中,通常需要对所有的请求设置统一的响应头,比如 "Content-Type": "application/json" 

    而在使用express和koa等框架时,通常会利用express-router和koa-router实现这一操作

    在express-router中的实现代码是

        let router = express.Router();
        router.use(function(req,res,next){
            res.set({
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Headers': 'Content-Type,accept',
                'Access-Control-Allow-Methods': 'GET,POST,OPTIONS',
                'Content-Type': 'application/json;charset=utf-8'
            });
            next();
        });

    在koa-router中的实现略有区别

      let Router = new KoaRouter()
      Router.use('/', async (ctx,next) => {
        ctx.response.set('Content-Type', 'application/json')
        await next()
      })
  • 相关阅读:
    171-滑动窗口问题
    170-133. 克隆图
    169-150. 逆波兰表达式求值
    windows相对路径设置与取消小工具[提效]
    Sword 38
    Sword 33
    Sword 28
    Sword 26
    Sword 12
    Sword 07
  • 原文地址:https://www.cnblogs.com/zhaozhipeng/p/8337544.html
Copyright © 2020-2023  润新知