Complete the code to start a basic HTTP server using Deno.serve.
import { serve } from "https://deno.land/std@0.177.0/http/server.ts"; serve({ port: [1] });
The standard port for many local HTTP servers is 8080. Here, you fill in the port number to start the server.
Complete the code to respond with 'Hello World' to every HTTP request.
import { serve } from "https://deno.land/std@0.177.0/http/server.ts"; serve(req => new Response([1]));
The Response constructor expects a string or a body as its first argument. We pass the string "Hello World" to create the response body.
Fix the error in the code to correctly handle HTTP requests and respond with JSON.
import { serve } from "https://deno.land/std@0.177.0/http/server.ts"; serve(req => { const data = { message: "Hi" }; return new Response(JSON.stringify([1]), { headers: { "Content-Type": "application/json" } }); });
We need to stringify the 'data' object to send it as JSON in the response body.
Fill both blanks to create a server that responds with the request method and URL in plain text.
import { serve } from "https://deno.land/std@0.177.0/http/server.ts"; serve(req => { const method = req.[1]; const url = req.[2]; return new Response(`Method: ${method}, URL: ${url}`); });
The request object has a 'method' property for HTTP method and a 'url' property for the full URL string.
Fill all three blanks to create a server that responds with JSON containing the request method, pathname, and a custom header value.
import { serve } from "https://deno.land/std@0.177.0/http/server.ts"; serve(req => { const url = new URL(req.[1]); const method = req.[2]; const customHeader = req.headers.get([3]); const responseData = { method: method, pathname: url.pathname, customHeader: customHeader }; return new Response(JSON.stringify(responseData), { headers: { "Content-Type": "application/json" } }); });
The request's URL string is in 'url', the HTTP method in 'method', and the custom header is accessed by its exact name as a string.
