Last active
September 15, 2021 03:42
-
-
Save kyouheicf/75e281f8d9e05b61894168ebf1651fe2 to your computer and use it in GitHub Desktop.
comment is added to code example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://developers.cloudflare.com/workers/examples/return-html | |
// The value of const can't be changed through reassignment | |
// Template literals allow us to define multiple lines using `` | |
const html = `<!DOCTYPE html> | |
<body> | |
<h1>Hello World</h1> | |
<p>This markup was generated by a Cloudflare Worker.</p> | |
</body>` | |
// async means that it return Promise at first, then return resolve/reject | |
// declaring function with request as a parameter | |
async function handleRequest(request) { | |
// The Response(body, init) constructor creates a new Response object | |
return new Response(html, { | |
headers: { | |
"content-type": "text/html;charset=UTF-8", | |
}, | |
}) | |
} | |
// addEventListener(type, listener) defines triggers for a Worker script to execute. | |
// type - Currently the only types supported are "fetch" and "scheduled". | |
// "fetch" as FetchEvent is the event type for HTTP requests dispatched to a Worker | |
// event ==> is ideal as function(event) | |
addEventListener("fetch", event => { | |
// event.request is the incoming HTTP request triggering FetchEvent | |
// event.respondWith(response) intercept the request and send a custom response | |
return event.respondWith(handleRequest(event.request)) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment