-
Notifications
You must be signed in to change notification settings - Fork 85
/
index.js
82 lines (65 loc) · 2.22 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { Router } from 'itty-router'
// Create a new router
const router = Router()
/*
Our index route, a simple hello world.
*/
router.get("/", () => {
return new Response("Hello, world! This is the root page of your Worker template.")
})
/*
This route demonstrates path parameters, allowing you to extract fragments from the request
URL.
Try visit /example/hello and see the response.
*/
router.get("/example/:text", ({ params }) => {
// Decode text like "Hello%20world" into "Hello world"
let input = decodeURIComponent(params.text)
// Construct a buffer from our input
let buffer = Buffer.from(input, "utf8")
// Serialise the buffer into a base64 string
let base64 = buffer.toString("base64")
// Return the HTML with the string to the client
return new Response(`<p>Base64 encoding: <code>${base64}</code></p>`, {
headers: {
"Content-Type": "text/html"
}
})
})
/*
This shows a different HTTP method, a POST.
Try send a POST request using curl or another tool.
Try the below curl command to send JSON:
$ curl -X POST <worker> -H "Content-Type: application/json" -d '{"abc": "def"}'
*/
router.post("/post", async request => {
// Create a base object with some fields.
let fields = {
"asn": request.cf.asn,
"colo": request.cf.colo
}
// If the POST data is JSON then attach it to our response.
if (request.headers.get("Content-Type") === "application/json") {
fields["json"] = await request.json()
}
// Serialise the JSON to a string.
const returnData = JSON.stringify(fields, null, 2);
return new Response(returnData, {
headers: {
"Content-Type": "application/json"
}
})
})
/*
This is the last route we define, it will match anything that hasn't hit a route we've defined
above, therefore it's useful as a 404 (and avoids us hitting worker exceptions, so make sure to include it!).
Visit any page that doesn't exist (e.g. /foobar) to see it in action.
*/
router.all("*", () => new Response("404, not found!", { status: 404 }))
/*
This snippet ties our worker to the router we deifned above, all incoming requests
are passed to the router where your routes are called and the response is sent.
*/
addEventListener('fetch', (e) => {
e.respondWith(router.handle(e.request))
})