Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
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
// This HTTP val will return HTML with a comment form and display all previous comments.
// Comments are saved in blob storage and will be displayed to all users.
import { blob } from "https://esm.town/v/std/blob";
const key = "comments";
export default async function main(req: Request): Promise<Response> {
if (req.method === "POST") {
// Handle comment submission
const formData = await req.formData();
const comment = formData.get("comment")?.toString();
if (comment) {
// Get current comments
const comments = await blob.getJSON<string[]>(key) ?? [];
// Add new comment to the list
comments.push(comment);
// Save updated comments
await blob.setJSON(key, comments);
}
// Redirect back to the main page
return Response.redirect("/", 302);
}
// Fetch current comments
const comments = await blob.getJSON<string[]>(key) ?? [];
// Construct HTML response
const html = `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Comment Box</title>
</head>
<body>
<h1>Comment Box</h1>
<form method="POST" action="/">
<textarea name="comment" rows="4" cols="50" required></textarea><br>
<input type="submit" value="Submit Comment">
</form>
<h2>Previous Comments</h2>
<ul>
${comments.map(comment => `<li>${comment}</li>`).join('')}
</ul>
</body>
</html>`;
return new Response(html, {
headers: { "Content-Type": "text/html" },
});
}
janpaul123-valle_tmp_3001062978969282023029581766561558.web.val.run
July 17, 2024