Assuming searchParams.get returns undefined instead of null
Not awaiting request.json() causing undefined name
Confusing query param key spacing (id vs id=)
4. What is wrong with this SvelteKit POST handler code?
export async function POST({ request }) {
const data = request.formData();
const username = data.get('username');
return new Response(username);
}
medium
A. Response should be JSON, not plain text
B. Using formData() instead of json() for JSON body
C. Cannot call get() on formData object
D. Missing await before request.formData()
Solution
Step 1: Check formData() usage
request.formData() returns a promise and must be awaited to get the FormData object.
Step 2: Identify missing await
The code calls request.formData() without await, so data is a promise, not a FormData instance, causing an error on data.get().
Final Answer:
Missing await before request.formData() -> Option D
Quick Check:
Always await async parsing methods like formData() [OK]
Hint: Always await request.formData() to get the data object [OK]
Common Mistakes:
Forgetting await leads to runtime errors
Confusing formData() with synchronous methods
Assuming formData() returns plain object
5. You want to handle a POST request in SvelteKit that can accept either JSON or form data. Which approach correctly parses the request body regardless of content type?
hard
A.
export async function POST({ request }) {
if (request.headers.get('content-type')?.includes('application/json')) {
const data = await request.json();
return new Response(JSON.stringify(data));
} else {
const form = await request.formData();
const obj = Object.fromEntries(form.entries());
return new Response(JSON.stringify(obj));
}
}
B.
export async function POST({ request }) {
const data = await request.json();
return new Response(JSON.stringify(data));
}
C.
export async function POST({ request }) {
const form = await request.formData();
return new Response(JSON.stringify(form));
}
D.
export async function POST({ request }) {
const text = await request.text();
return new Response(text);
}
Solution
Step 1: Check content-type header
The code checks if the request content type includes 'application/json' to decide parsing method.
Step 2: Parse accordingly
If JSON, it uses request.json(). Otherwise, it uses request.formData() and converts form entries to an object.
Step 3: Return consistent JSON response
Both branches return JSON stringified data, handling both content types correctly.
Final Answer:
Conditional parsing based on content-type header -> Option A
Quick Check:
Check content-type to parse JSON or form data [OK]
Hint: Check content-type header to choose parsing method [OK]
Common Mistakes:
Assuming all requests are JSON or form data only
Not converting formData to object before JSON.stringify
Ignoring content-type leads to parsing errors
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.