Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a GET handler that returns a JSON response.
Deno
import { serve } from "https://deno.land/std@0.177.0/http/server.ts"; serve(async (req) => { if (req.method === "GET") { return new Response(JSON.stringify({ message: "Hello World" }), { headers: { "Content-Type": [1] } }); } return new Response(null, { status: 405 }); });
Attempts:
3 left
💡 Hint
Common Mistakes
Using "text/html" or "text/plain" as Content-Type for JSON response.
Forgetting to stringify the JSON object.
✗ Incorrect
The Content-Type header must be set to "application/json" to indicate the response is JSON.
2fill in blank
mediumComplete the code to parse JSON data from a POST request.
Deno
serve(async (req) => {
if (req.method === "POST") {
const data = await req.[1]();
return new Response(JSON.stringify({ received: data }), {
headers: { "Content-Type": "application/json" }
});
}
return new Response(null, { status: 405 });
});Attempts:
3 left
💡 Hint
Common Mistakes
Using req.text() which returns raw text instead of parsed JSON.
Using req.formData() which is for form submissions.
✗ Incorrect
To get JSON data from the request, use req.json() which returns a parsed object.
3fill in blank
hardFix the error in the handler to correctly respond with status 404 when the path is not found.
Deno
serve((req) => {
const url = new URL(req.url);
if (url.pathname === "/data") {
return new Response("Data found", { status: 200 });
} else {
return new Response("Not found", { status: [1] });
}
});Attempts:
3 left
💡 Hint
Common Mistakes
Using 200 status code for not found response.
Using 500 which means server error.
✗ Incorrect
Status code 404 means the requested resource was not found, which is correct here.
4fill in blank
hardFill both blanks to create a handler that responds with JSON only for GET requests and returns 405 for others.
Deno
serve((req) => {
if (req.method === [1]) {
return new Response(JSON.stringify({ status: "ok" }), {
headers: { "Content-Type": [2] }
});
}
return new Response(null, { status: 405 });
});Attempts:
3 left
💡 Hint
Common Mistakes
Checking for POST instead of GET.
Using wrong Content-Type header.
✗ Incorrect
The handler should check for GET method and respond with JSON content type.
5fill in blank
hardFill all three blanks to create a POST handler that reads JSON, extracts 'name', and returns a greeting.
Deno
serve(async (req) => {
if (req.method === [1]) {
const data = await req.[2]();
const name = data.[3] || "Guest";
return new Response(JSON.stringify({ greeting: `Hello, ${name}!` }), {
headers: { "Content-Type": "application/json" }
});
}
return new Response(null, { status: 405 });
});Attempts:
3 left
💡 Hint
Common Mistakes
Checking for GET instead of POST.
Using req.text() instead of req.json().
Accessing wrong property name.
✗ Incorrect
The handler must check for POST, parse JSON with req.json(), and access the 'name' property.
