第1+周 1-7合并路由的问题

来源:2-9 工作目录介绍、合并路由、静态资源服务【进阶篇】

jobor

2020-12-25 16:12:11

# 具体遇到的问题

之前的小节里,使用路由:

const Router = require('koa-router')

const router = new Router();


app.use(router.routes())

    .use(router.allowedMethods());

app.listen(3000)

查看api可以看到这两个方法:

 router.routes(),Returns router middleware which dispatches a route matching the request。


 router.allowedMethods(),Returns separate middleware for responding to OPTIONS requests with an Allow header containing the allowed methods, as well as responding with 405 Method Not Allowed and 501 Not Implemented as appropriate.


这里我理解的是 router.routes() 用来匹配请求路径,router.allowedMethods() 是一个拦截器,对于没有定义的请求路径返回 4xx 或 5xx 状态。


那么在这一小节里,使用 koa-combine-routes 合并路由:

// src/routes/routes.js

const combineRoutes = require('koa-combine-routers')

const aroutes = require('./aRouter')

const broutes = require('./bRouter')

module.exports = combineRoutes(

  aroutes,

  broutes

)


// src/index.js

const Koa = require('koa')

const app = new Koa()

const router = require('./routes/routes')

app.use(router());

app.listen(3000)



这里不需要再 router.routes() 是因为 koa-combine-routes 这个中间件里内置了相关方法吗?但是 combineRoutes 合并之后返回的是一个方法,拦截器没法使用了,如果还想用拦截器该怎么办呢?

写回答

1回答

Brian

2020-12-29

是因为 koa-combine-routes 这个中间件里内置了相关方法吗?

——是的


但是 combineRoutes 合并之后返回的是一个方法,拦截器没法使用了,如果还想用拦截器该怎么办呢?

——可以自己开发一个koa的中间件啊,参考后面的课程

0

0 学习 · 1842 问题

查看课程