Bird
Raised Fist0
Denoframework~10 mins

Request and Response objects in Deno - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Request and Response objects
Client sends HTTP request
↓
Server receives Request object
↓
Server reads Request properties
↓
Server processes data
↓
Server creates Response object
↓
Server sends Response back to client
↓
Client receives Response
This flow shows how a server in Deno handles an incoming HTTP request using the Request object, processes it, then sends back a Response object.
Execution Sample
Deno
const handler = async (req) => {
  const url = new URL(req.url);
  if (url.pathname === "/hello") {
    return new Response("Hello World", { status: 200 });
  }
  return new Response("Not Found", { status: 404 });
};
This code checks the request URL path and returns a Response with 'Hello World' if path is '/hello', otherwise 'Not Found'.
Execution Table
StepActionRequest.urlConditionResponse CreatedStatus CodeResponse Body
1Receive requesthttp://localhost/hellourl.pathname === '/hello' ?No
2Check conditionhttp://localhost/hellotrueYes200"Hello World"
3Send responsehttp://localhost/helloYes200"Hello World"
4Receive requesthttp://localhost/byeurl.pathname === '/hello' ?No
5Check conditionhttp://localhost/byefalseYes404"Not Found"
6Send responsehttp://localhost/byeYes404"Not Found"
💡 Execution stops after sending the Response object back to the client.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 4After Step 5Final
req.urlundefinedhttp://localhost/hellohttp://localhost/hellohttp://localhost/byehttp://localhost/byehttp://localhost/bye
url.pathnameundefined/hello/hello/bye/bye/bye
Response.statusundefinedundefined200undefined404404
Response.bodyundefinedundefined"Hello World"undefined"Not Found""Not Found"
Key Moments - 2 Insights
Why does the server return a 404 status for the path '/bye'?
Because in the execution_table at Step 5, the condition url.pathname === '/hello' is false, so the else branch returns a Response with status 404.
What part of the Request object do we use to decide the response?
We use req.url, specifically the pathname part extracted by new URL(req.url).pathname, as shown in Steps 1 and 2 in the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 2. What is the Response status code created?
A404
B200
C500
D302
💡 Hint
Check the 'Status Code' column at Step 2 in the execution_table.
At which step does the condition url.pathname === '/hello' become false?
AStep 2
BStep 4
CStep 5
DStep 6
💡 Hint
Look at the 'Condition' column in the execution_table rows for Step 5.
If the request URL was 'http://localhost/hello', what would be the Response body at Step 3?
A"Hello World"
B"Error"
C"Not Found"
D"Welcome"
💡 Hint
Refer to the 'Response Body' column at Step 3 in the execution_table.
Concept Snapshot
Request and Response objects in Deno:
- Request object holds client HTTP request info (e.g., URL).
- Use new URL(req.url) to parse the request URL.
- Create Response object with body and status to reply.
- Server sends Response back to client.
- Common pattern: check req.url, return Response accordingly.
Full Transcript
In Deno, when a client sends an HTTP request, the server receives it as a Request object. The server reads the URL from the Request to decide what to do. For example, if the path is '/hello', the server returns a Response object with status 200 and body 'Hello World'. If the path is anything else, it returns a Response with status 404 and body 'Not Found'. This process involves reading the Request.url, checking conditions, creating a Response, and sending it back to the client. The execution table shows each step, including receiving the request, checking the URL path, creating the response, and sending it. Variables like req.url and Response.status change as the code runs. Understanding this flow helps beginners see how servers handle requests and send responses in Deno.

Practice

(1/5)
1. What does the Request object represent in a Deno web server?
easy
A. The data sent by the server to the user
B. The server's file system access
C. The server configuration settings
D. The data sent by the user to the server

Solution

  1. 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.
  2. Step 2: Differentiate from Response object

    The Response object is what the server sends back, so it is not the Request.
  3. Final Answer:

    The data sent by the user to the server -> Option D
  4. Quick Check:

    Request = user data [OK]
Hint: Request = user input; Response = server output [OK]
Common Mistakes:
  • Confusing Request with Response
  • Thinking Request holds server settings
  • Assuming Request is server output
2. Which of the following is the correct way to create a Response object with a JSON body in Deno?
easy
A. Response.json(data)
B. new Response(data, { type: 'json' })
C. new Response(data, { headers: { 'Content-Type': 'application/json' } })
D. new Response(data, { contentType: 'application/json' })

Solution

  1. 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'.
  2. 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.
  3. Final Answer:

    new Response(data, { headers: { 'Content-Type': 'application/json' } }) -> Option C
  4. Quick Check:

    Response with JSON header [OK]
Hint: Use new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } }) [OK]
Common Mistakes:
  • Passing raw object without stringify
  • Using incorrect init properties like 'type' or 'contentType'
  • Assuming Response.json() exists
3. Given the following Deno server code snippet, what will be the response body when a user sends a GET request?
const handler = (req) => {
  if (req.method === 'GET') {
    return new Response('Hello World');
  }
  return new Response('Method Not Allowed', { status: 405 });
};
medium
A. "Method Not Allowed"
B. "Hello World"
C. Empty response
D. Error thrown

Solution

  1. Step 1: Check request method condition

    The code checks if the request method is 'GET'. If yes, it returns 'Hello World'.
  2. Step 2: Determine response for GET request

    Since the user sends a GET request, the first condition matches and returns 'Hello World'.
  3. Final Answer:

    "Hello World" -> Option B
  4. Quick Check:

    GET request returns 'Hello World' [OK]
Hint: Check req.method to decide response content [OK]
Common Mistakes:
  • Ignoring method check and picking wrong response
  • Assuming default response is empty
  • Thinking error is thrown on GET
4. Identify the error in this Deno request handler code:
const handler = (req) => {
  if (req.method = 'POST') {
    return new Response('Posted');
  }
  return new Response('Not Posted');
};
medium
A. Using assignment (=) instead of comparison (===) in if condition
B. Missing await keyword before Response
C. Response body must be JSON, not string
D. req.method is undefined

Solution

  1. Step 1: Check the if condition syntax

    The code uses single equals (=) which assigns 'POST' to req.method instead of comparing it.
  2. Step 2: Understand correct comparison operator

    To compare, use '===' or '==' instead of '=' to avoid bugs.
  3. Final Answer:

    Using assignment (=) instead of comparison (===) in if condition -> Option A
  4. Quick Check:

    Use '===' for comparison, not '=' [OK]
Hint: Use '===' for comparisons, '=' is assignment [OK]
Common Mistakes:
  • Confusing assignment and comparison operators
  • Thinking Response needs await here
  • Assuming req.method is missing
5. How can you read JSON data sent in the body of a POST request using the Deno Request object?
hard
A. Use await req.json() to parse the JSON body
B. Use req.body.json() without await
C. Use JSON.parse(req.body) directly
D. Use req.getJson() method

Solution

  1. 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.
  2. Step 2: Confirm correct usage

    You must await req.json() because it returns a Promise resolving to the parsed object.
  3. Final Answer:

    Use await req.json() to parse the JSON body -> Option A
  4. Quick Check:

    await req.json() parses JSON body correctly [OK]
Hint: Always await req.json() to get JSON body [OK]
Common Mistakes:
  • Calling json() without await
  • Trying to parse req.body directly
  • Using non-existent getJson() method
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard