vtdocs-renderformandsavedata.express.val.run
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
import { set } from "https://esm.town/v/std/set?v=11";
import { email } from "https://esm.town/v/std/email?v=9";
let { submittedEmailAddresses } = await import("https://esm.town/v/vtdocs/submittedEmailAddresses");
export const renderFormAndSaveData = async (
req: express.Request,
res: express.Response,
) => {
// A visit from a web browser? Serve a HTML page with a form
if (req.method === "GET") {
return res.send(`
<!DOCTYPE html>
<html>
<head>
<title>Email Form</title>
</head>
<body>
<!-- Change the action here to THIS val's Express endpoint! -->
<form action="https://vtdocs-renderFormAndSaveData.express.val.run" method="post">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
`);
}
// Otherwise, someone has submitted a form so let's handle that
if (submittedEmailAddresses === undefined) {
submittedEmailAddresses = [];
}
const emailAddress = req.body.email;
if (submittedEmailAddresses.includes(emailAddress)) {
return res.send("you're already signed up!");
}
await email({
text: `${emailAddress} just signed up!`,
subject: "new sign up",
});
submittedEmailAddresses.push(emailAddress);
await set(
"submittedEmailAddresses",
submittedEmailAddresses,
);
return res.send("thanks! you're signed up!");
};
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
v9
October 23, 2023