Public
HTTP (deprecated)
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
import { blob } from "https://esm.town/v/std/blob";
export default async (request) => {
// Function to create a standard response with CORS headers
const createResponse = (body, status = 200) => {
return new Response(body, {
status,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*", // Allow any origin
"Access-Control-Allow-Methods": "GET, POST, OPTIONS", // Allow these methods
"Access-Control-Allow-Headers": "Content-Type", // Allow these headers
},
});
};
try {
if (request.method === "POST") {
const formData = await request.json();
// Check if all required fields are present
if (!formData.title || !formData.description || !formData.youtubeUrl || !formData.date || !formData.speakerName) {
return createResponse(JSON.stringify({ error: "Missing required fields" }), 400);
}
// Store the data in Blob storage
await blob.setJSON("latestFormData", formData);
return createResponse(JSON.stringify({ message: "Data received and stored successfully" }));
}
if (request.method === "GET") {
// Retrieve the stored data from Blob storage
const storedData = await blob.getJSON("latestFormData");
if (!storedData) {
return createResponse(JSON.stringify({ error: "No data available" }), 404);
}
return createResponse(JSON.stringify(storedData));
}
if (request.method === "OPTIONS") {
// Handle OPTIONS requests for CORS preflight
return createResponse(null, 204);
}
// If the request method is neither POST nor GET, return an error
return createResponse(JSON.stringify({ error: "Invalid request method" }), 405);
} catch (error) {
console.error("Error handling request:", error);
return createResponse(JSON.stringify({ error: `An error occurred: ${error.message}` }), 500);
}
};
mvmattgray-supremeredcrane.web.val.run
August 27, 2024