Data fetching with handlers lets your server get information when someone asks for it. It helps your app show fresh data from other places like APIs or databases.
Data fetching with handlers in Deno
import { serve } from "https://deno.land/std@0.177.0/http/server.ts"; serve(async (req) => { // Your handler code here return new Response("Hello World"); });
The serve function starts a server and listens for requests.
The handler is an async function that takes a request and returns a response.
import { serve } from "https://deno.land/std@0.177.0/http/server.ts"; serve(async (req) => { return new Response("Simple response"); });
import { serve } from "https://deno.land/std@0.177.0/http/server.ts"; serve(async (req) => { const url = new URL(req.url); if (url.pathname === "/data") { const data = { message: "Hello from server" }; return new Response(JSON.stringify(data), { headers: { "Content-Type": "application/json" }, }); } return new Response("Not Found", { status: 404 }); });
This server listens for requests. If the path is '/greet' and has a 'name' query, it says hello with that name. Otherwise, it shows a 404 message.
import { serve } from "https://deno.land/std@0.177.0/http/server.ts"; serve(async (req) => { const url = new URL(req.url); if (url.pathname === "/greet") { const name = url.searchParams.get("name") || "friend"; const message = `Hello, ${name}! Welcome to Deno server.`; return new Response(message, { headers: { "Content-Type": "text/plain; charset=utf-8" }, }); } return new Response("Page not found", { status: 404 }); });
Always set the correct Content-Type header so browsers know how to handle the response.
Use async functions to fetch data from databases or APIs inside the handler.
Remember to handle different URL paths to serve different data or pages.
Data fetching with handlers lets your server respond with fresh data when asked.
Use the serve function with an async handler to process requests.
Check the request URL to decide what data to send back.
Practice
serve in Deno for data fetching?Solution
Step 1: Understand the role of
Theserveand handlerservefunction listens for incoming HTTP requests and uses the handler function to decide how to respond.Step 2: Identify the handler's purpose
The handler processes each request and returns the correct response, such as data or status messages.Final Answer:
To process incoming requests and send back appropriate responses -> Option DQuick Check:
Handler processes requests = D [OK]
- Thinking handler creates database connections automatically
- Confusing handler with styling or compilation tasks
- Assuming serve compiles code
handler?Solution
Step 1: Recall the
In Deno,servefunction usageserveis called with the handler function as an argument to start the server.Step 2: Check syntax correctness
The correct syntax isserve(handler);which passes the handler function properly.Final Answer:
serve(handler); -> Option BQuick Check:
serve called with handler function = C [OK]
- Using assignment instead of function call
- Trying to call serve as a method on handler
- Using invalid arrow syntax
async function handler(req) {
if (req.url.endsWith('/hello')) {
return new Response('Hello World');
}
return new Response('Not Found', { status: 404 });
}What will the server respond when a request is made to
http://localhost:8000/hello?Solution
Step 1: Analyze the URL condition in handler
The handler checks if the request URL ends with '/hello'. If yes, it returns 'Hello World'.Step 2: Match the request URL
The request URL is exactly '/hello', so the condition is true and the response is 'Hello World'.Final Answer:
A response with body 'Hello World' -> Option AQuick Check:
URL ends with '/hello' returns 'Hello World' = B [OK]
- Assuming 404 because of missing else
- Thinking response body is empty
- Expecting runtime error from this code
async function handler(req) {
if (req.url === '/data') {
const data = await fetch('https://api.example.com/data');
return data.json();
}
return new Response('Not Found', { status: 404 });
}Solution
Step 1: Understand fetch and response handling
The fetch returns a Response object; callingdata.json()returns a Promise that must be awaited.Step 2: Identify missing await
The code returnsdata.json()without awaiting it, which returns a Promise instead of a Response object.Final Answer:
Missing await before data.json() -> Option CQuick Check:
Await JSON parsing Promise = A [OK]
- Thinking fetch is disallowed in handlers
- Using req.path instead of req.url
- Believing 404 status is invalid
/user. Which handler function correctly fetches the JSON data and returns it as a JSON response?Solution
Step 1: Check correct async handling and URL matching
async function handler(req) { if (req.url.endsWith('/user')) { const response = await fetch('https://api.example.com/user'); const data = await response.json(); return new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } }); } return new Response('Not Found', { status: 404 }); } usesendsWith('/user')to match URL and awaits both fetch and response.json(), which is correct.Step 2: Verify response formatting
async function handler(req) { if (req.url.endsWith('/user')) { const response = await fetch('https://api.example.com/user'); const data = await response.json(); return new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } }); } return new Response('Not Found', { status: 404 }); } returns a new Response with JSON string and correct Content-Type header, ensuring proper JSON response.Final Answer:
Option A correctly fetches and returns JSON data with proper async handling and headers -> Option AQuick Check:
Await fetch and json, set JSON header = A [OK]
- Not awaiting response.json()
- Returning raw Promise instead of Response
- Missing Content-Type header for JSON
- Using non-async function with await
Ready to prove it?
Pass the test and this pattern moves unknown
