Complete the code to create a new HTTP server that listens on port 8000.
import { serve } from "https://deno.land/std/http/server.ts"; serve((req) => new Response("Hello World"), { port: [1] });
The serve function starts an HTTP server on the specified port. Here, port 8000 is the standard example port.
Complete the code to read the HTTP method from the incoming request object.
serve((req) => {
const method = req.[1];
return new Response(`Method is ${method}`);
});url instead of method.The method property of the request object tells us if the request is GET, POST, etc.
Fix the error in the code to correctly return a JSON response with status 200.
serve((req) => {
return new Response(JSON.stringify({ message: "OK" }), {
status: [1],
headers: { "Content-Type": "application/json" }
});
});Status code 200 means the request was successful and the response contains the expected data.
Fill both blanks to extract the JSON body from the request and respond with a message.
serve(async (req) => {
const data = await req.[1]();
return new Response(`Hello, ${data.[2]`);
});text() instead of json() to read JSON data.body directly without parsing.The json() method reads the request body as JSON. Then we access the name property from the parsed data.
Fill all three blanks to create a response with a custom header and status code.
serve((req) => {
return new Response("Custom header set", {
status: [1],
headers: { [2]: [3] }
});
});Status 200 means success. The header key is X-Custom-Header and the value is MyValue. This shows how to add custom headers to a response.
