更新日:

Cloudflare Workers ルーティングライブラリ itty-router

タグ

ソースコード

package.json
{
  "main": "src/index.js",
  "scripts": {
    "start": "wrangler dev",
    "deploy": "wrangler publish"
  },
  "devDependencies": {
    "@cloudflare/wrangler": "^1.15.0"
  },
  "dependencies": {
    "itty-router": "^2.3.10"
  }
}
src/index.js
import { Router } from 'itty-router';
const router = Router();

router.get(
  '/todos/:id',
  ({ params }) => new Response(JSON.stringify({ id: params.id }))
);

router.post('/todos', async request => {
  const content = await request.json();
  return new Response(JSON.stringify(content));
});

router.all('*', () => new Response('not found', { status: 404 }));

addEventListener('fetch', event =>
  event.respondWith(router.handle(event.request))
);
wrangler.toml
name = "プロジェクト名"
type = "webpack"
account_id = "アカウントID"
workers_dev = true
route = ""
zone_id = ""

© 2020- itsumen.com