鍍金池/ 問答/HTML/ koa-router如何匹配任意路徑

koa-router如何匹配任意路徑

clipboard.png

我想這一塊匹配上面沒有匹配到的所有路由,可是我這樣的做法并沒有什么亂用。

剛開始使用,希望有人指點一下,謝謝

回答
編輯回答
好難瘦

koa-router 的 README 里有說明,"Route paths will be translated to regular expressions using path-to-regexp"

使用 router.get('/(.*)')

可以用這個工具測試 route express-route-tester


看你的代碼,是想將不支持的 url 都轉到錯誤頁去。
一般的做法是寫個 koa 的中間件,去處理 404,而不是寫個 route 去涵蓋“不支持的 url”

app.use(router.routes(), router.allowedMethods())

// handle 404 etc.
app.use(async (ctx, next) => {
  try {
    await next()
    if (ctx.status === 404) {
      // do somthing here
    }
  } catch (err) {
    // handle error
  }
})
2017年5月9日 11:13
編輯回答
不舍棄

使用 * 或 use

router.get('*', ...)

app.use(...)

2017年11月24日 08:48