routes(route_config)
route_config : オブジェクトの配列
path: マッチするパス (配列可)- 正規表現 or 文字列
- 文字列の場合は最初の
/省略可 - 文字列の場合は
<name>でパラメータ - パラメータの最後に
/を入れると/はマッチしなくなる
method: マッチするメソッド (配列可)handler: ミドルウェア関数 (配列可)
返り値: ミドルウェア関数
const Koa = require("koa")
const routes = require("./routes.js")
const app = new Koa()
app.use(
routes([
{
path: "/",
method: "GET",
handler(ctx) {
ctx.body = "A"
},
},
{
path: ["/a", "/b"],
method: ["GET", "POST"],
handler: [
(ctx, next) => {
ctx.body = "M"
return next()
},
ctx => (ctx.body += "B"),
],
},
{
path: /^\/c\/xx-(?<id>[a-z]+)-yy\/zz$/,
handler(ctx) {
ctx.body = ctx.params
}
},
{
path: "/d/xx-<id>-yy/zz",
handler(ctx) {
ctx.body = ctx.params
}
},
{
path: "e/zz<param>",
handler(ctx) {
ctx.body = ctx.params
}
},
{
path: "f/zz<param/>",
handler(ctx) {
ctx.body = ctx.params
}
},
{
handler(ctx) {
ctx.body = "NOTFOUND"
}
},
])
)
app.listen(80)リクエスト
const request = async (path, method) => {
const res = await fetch(path, { method })
const body = await res.text()
return console.log(body)
}
await request("/")
// "A"
await request("/", "POST")
// "NOTFOUND"
await request("/a")
// "MB"
await request("/a", "POST")
// "MB"
await request("/b")
// "MB"
await request("/b", "POST")
// "MB"
await request("/c/xx-abcd-yy/zz")
// "{"id":"abcd","match1":"abcd"}"
await request("/d/xx-123-yy/zz")
// "{"id":"123","match1":"123"}"
await request("/e/zz1/2/3/4")
// "{"param":"1/2/3/4","match1":"1/2/3/4"}"
await request("/f/zz1/2/3/4")
// "NOTFOUND"
await request("/f/zz1234")
// "{"param":"1234","match1":"1234"}"