Request and Response objects let your server talk with users. The Request holds what the user sends. The Response is what your server sends back.
Request and Response objects in Deno
async function handler(request: Request): Promise<Response> { // Use request to read user data // Create and return a Response return new Response('Hello world', { status: 200 }); }
The Request object contains info about the user's request like method, headers, and body.
The Response object is what you send back. You create it with content, status, and headers.
const handler = async (request: Request): Promise<Response> => { const url = new URL(request.url); return new Response(`You asked for: ${url.pathname}`); };
const handler = async (request: Request): Promise<Response> => { if (request.method === 'POST') { const data = await request.json(); return new Response(`Got data: ${JSON.stringify(data)}`); } return new Response('Send a POST request'); };
const handler = (request: Request): Response => {
return new Response('Not Found', { status: 404 });
};This Deno server listens on port 8000. It handles GET requests to /hello by sending a greeting. It handles POST requests to /data by reading JSON data and replying with it. Other requests get a 404 response.
import { serve } from "https://deno.land/std@0.201.0/http/server.ts"; const handler = async (request: Request): Promise<Response> => { const { pathname } = new URL(request.url); if (request.method === "GET" && pathname === "/hello") { return new Response("Hello from Deno!", { status: 200, headers: { "content-type": "text/plain; charset=utf-8" }, }); } if (request.method === "POST" && pathname === "/data") { try { const data = await request.json(); return new Response(`Received data: ${JSON.stringify(data)}`, { status: 200, headers: { "content-type": "application/json" }, }); } catch { return new Response("Invalid JSON", { status: 400 }); } } return new Response("Not Found", { status: 404 }); }; console.log("Server running on http://localhost:8000"); serve(handler, { port: 8000 });
Always check the request method (GET, POST, etc.) before reading the body.
Use await request.json() to read JSON data safely.
Set proper content-type headers in your Response for better browser handling.
Request objects hold what the user sends to your server.
Response objects are what your server sends back to the user.
Use these objects to build interactive and data-driven web servers in Deno.
Practice
Request object represent in a Deno web server?Solution
Step 1: Understand the role of Request object
The Request object contains information about what the user sends to the server, such as headers, method, and body.Step 2: Differentiate from Response object
The Response object is what the server sends back, so it is not the Request.Final Answer:
The data sent by the user to the server -> Option DQuick Check:
Request = user data [OK]
- Confusing Request with Response
- Thinking Request holds server settings
- Assuming Request is server output
Solution
Step 1: Check how to send JSON in Response
In Deno, you can create a Response with JSON by stringifying the data and setting the 'Content-Type' header to 'application/json'.Step 2: Validate options
new Response(data, { headers: { 'Content-Type': 'application/json' } }) correctly sets the header and passes data (assuming data is stringified). Response.json(data) is invalid because Response.json() is not a standard method in Deno's Response API. Options B and D use incorrect properties.Final Answer:
new Response(data, { headers: { 'Content-Type': 'application/json' } }) -> Option CQuick Check:
Response with JSON header [OK]
- Passing raw object without stringify
- Using incorrect init properties like 'type' or 'contentType'
- Assuming Response.json() exists
const handler = (req) => {
if (req.method === 'GET') {
return new Response('Hello World');
}
return new Response('Method Not Allowed', { status: 405 });
};Solution
Step 1: Check request method condition
The code checks if the request method is 'GET'. If yes, it returns 'Hello World'.Step 2: Determine response for GET request
Since the user sends a GET request, the first condition matches and returns 'Hello World'.Final Answer:
"Hello World" -> Option BQuick Check:
GET request returns 'Hello World' [OK]
- Ignoring method check and picking wrong response
- Assuming default response is empty
- Thinking error is thrown on GET
const handler = (req) => {
if (req.method = 'POST') {
return new Response('Posted');
}
return new Response('Not Posted');
};Solution
Step 1: Check the if condition syntax
The code uses single equals (=) which assigns 'POST' to req.method instead of comparing it.Step 2: Understand correct comparison operator
To compare, use '===' or '==' instead of '=' to avoid bugs.Final Answer:
Using assignment (=) instead of comparison (===) in if condition -> Option AQuick Check:
Use '===' for comparison, not '=' [OK]
- Confusing assignment and comparison operators
- Thinking Response needs await here
- Assuming req.method is missing
Request object?Solution
Step 1: Understand how to parse JSON body in Deno
The Request object has an async method json() that returns the parsed JSON from the body.Step 2: Confirm correct usage
You must await req.json() because it returns a Promise resolving to the parsed object.Final Answer:
Use await req.json() to parse the JSON body -> Option AQuick Check:
await req.json() parses JSON body correctly [OK]
- Calling json() without await
- Trying to parse req.body directly
- Using non-existent getJson() method
Ready to prove it?
Pass the test and this pattern moves unknown
