HTTP路由器 本文介绍如何根据不同的HTTP路由,响应对应内容。 根据不同的HTTP路由,响应对应内容。 示例代码 javascript addEventListener("fetch", (event) > { event.respondWith( handleRequest(event.request).catch( (err) > new Response(err.stack, { status: 500 }) ) ); }); async function handleRequest(request) { const { pathname } new URL(request.url); if (pathname.startsWith("/api")) { return new Response(JSON.stringify({ pathname }), { headers: { "ContentType": "application/json" }, }); } if (pathname.startsWith("/status")) { const httpStatusCode Number(pathname.split("/")[2]); return Number.isInteger(httpStatusCode) ? fetch(" + httpStatusCode) : new Response("That's not a valid HTTP status code."); } return new Response("This is a http router example!"); } 示例预览 在浏览器地址栏中输入匹配到HTTP路由的URL,即可预览示例效果。 相关参考 运行时API:addEventListener 运行时API:Response 运行时API:FetchEvent 运行时API:Web Standards