Bird
Raised Fist0
Svelteframework~20 mins

Request parsing in Svelte - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Request Parsing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Svelte component when submitting the form?

Consider this Svelte component that parses a form submission request. What will be logged to the console when the user submits the form with name="Alice" and age="30"?

Svelte
  <script>
    let name = '';
    let age = '';

    async function handleSubmit(event) {
      event.preventDefault();
      const formData = new FormData(event.target);
      const data = Object.fromEntries(formData.entries());
      console.log(data);
    }
  </script>

  <form on:submit={handleSubmit} aria-label="User info form">
    <label for="name">Name:</label>
    <input id="name" name="name" bind:value={name} required />

    <label for="age">Age:</label>
    <input id="age" name="age" type="number" bind:value={age} required />

    <button type="submit">Submit</button>
  </form>
ASyntaxError due to missing await
B{"name": "Alice", "age": "30"}
C{"name": "", "age": ""}
D{"name": "Alice", "age": 30}
Attempts:
2 left
💡 Hint

Remember that FormData entries are always strings.

📝 Syntax
intermediate
2:00remaining
Which option correctly parses JSON request body in a SvelteKit endpoint?

Given a SvelteKit endpoint, which code snippet correctly parses the JSON body from the request?

Svelte
export async function POST({ request }) {
  // parse JSON body here
}
Aconst data = await request.json(); return new Response(JSON.stringify(data));
Bconst data = JSON.parse(request.body); return new Response(JSON.stringify(data));
Cconst data = request.body.json(); return new Response(JSON.stringify(data));
Dconst data = await request.text(); return new Response(JSON.parse(data));
Attempts:
2 left
💡 Hint

Check the correct method to parse JSON from the request object.

🔧 Debug
advanced
2:00remaining
Why does this SvelteKit endpoint fail to parse form data correctly?

Examine this SvelteKit POST endpoint code. Why does it fail to parse the form data sent as application/x-www-form-urlencoded?

Svelte
export async function POST({ request }) {
  const data = await request.json();
  return new Response(JSON.stringify(data));
}
ABecause request.json() cannot parse urlencoded form data, it expects JSON content type.
BBecause request.body is empty and needs to be read as text first.
CBecause the endpoint must use request.formData() instead of request.json() for form data.
DBecause the response must be a redirect, not a JSON response.
Attempts:
2 left
💡 Hint

Consider the content type of the request and the method used to parse it.

❓ state_output
advanced
2:00remaining
What is the value of the variable 'parsed' after this SvelteKit endpoint runs?

Given this SvelteKit POST endpoint, what is the value of parsed after execution if the request body is JSON {"color":"blue","count":5}?

Svelte
export async function POST({ request }) {
  const parsed = await request.json();
  return new Response(JSON.stringify(parsed));
}
Aundefined
B{"color":"blue","count":"5"}
C{"color":"blue","count":5}
DSyntaxError
Attempts:
2 left
💡 Hint

JSON parsing preserves data types for numbers and strings.

🧠 Conceptual
expert
3:00remaining
Which option correctly explains how SvelteKit handles request parsing for different content types?

In SvelteKit, how does the framework handle parsing of incoming request bodies for different content types like JSON and form data?

ASvelteKit automatically parses all request bodies and provides a unified object in the endpoint handler.
BSvelteKit only supports JSON request bodies and throws errors for other content types.
CSvelteKit requires manual parsing of the raw request body stream for all content types using <code>request.text()</code>.
DSvelteKit provides methods like <code>request.json()</code> for JSON and <code>request.formData()</code> for form data, which must be called explicitly to parse the body accordingly.
Attempts:
2 left
💡 Hint

Think about the methods available on the request object for parsing.

Practice

(1/5)
1. In SvelteKit, which method is used to parse JSON data from a request object?
easy
A. request.formData()
B. request.text()
C. request.json()
D. request.body()

Solution

  1. Step 1: Understand request data types

    JSON data is structured and requires parsing to convert it into usable JavaScript objects.
  2. Step 2: Identify the correct parsing method

    request.json() is the built-in method to parse JSON body content from a request.
  3. Final Answer:

    request.json() -> Option C
  4. Quick Check:

    JSON parsing method = request.json() [OK]
Hint: Use request.json() to parse JSON bodies quickly [OK]
Common Mistakes:
  • Using request.text() for JSON causes manual parsing errors
  • Confusing formData() with JSON parsing
  • Assuming request.body() returns parsed data
2. Which of the following is the correct way to parse form data from a request in SvelteKit?
easy
A. const data = await request.json()
B. const data = await request.formData()
C. const data = request.body()
D. const data = request.text()

Solution

  1. Step 1: Identify form data parsing method

    Form data is sent as key-value pairs, often from HTML forms, and requires formData() to parse.
  2. Step 2: Confirm correct syntax

    The method await request.formData() returns a FormData object representing the form fields.
  3. Final Answer:

    const data = await request.formData() -> Option B
  4. Quick Check:

    Form data parsing = request.formData() [OK]
Hint: Use request.formData() to get form fields easily [OK]
Common Mistakes:
  • Using request.json() for form data causes errors
  • Forgetting to await the formData() promise
  • Trying to access request.body() directly
3. Given this SvelteKit handler code:
export async function POST({ request, url }) {
  const jsonData = await request.json();
  const searchParam = url.searchParams.get('id');
  return new Response(`ID: ${searchParam}, Name: ${jsonData.name}`);
}

What will be the response text if the request body is {"name":"Alice"} and the URL is /api?id=42?
medium
A. ID: 42, Name: Alice
B. ID: null, Name: Alice
C. ID: 42, Name: undefined
D. ID: , Name: Alice

Solution

  1. Step 1: Parse JSON body

    The code uses await request.json() to get { name: 'Alice' } from the request body.
  2. Step 2: Extract query parameter

    url.searchParams.get('id') reads the 'id' parameter from the URL, which is '42'.
  3. Step 3: Construct response string

    The response text combines both values: "ID: 42, Name: Alice".
  4. Final Answer:

    ID: 42, Name: Alice -> Option A
  5. Quick Check:

    Parsed JSON and query param combined = ID: 42, Name: Alice [OK]
Hint: Remember url.searchParams.get('key') reads query strings [OK]
Common Mistakes:
  • 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

  1. Step 1: Check formData() usage

    request.formData() returns a promise and must be awaited to get the FormData object.
  2. 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().
  3. Final Answer:

    Missing await before request.formData() -> Option D
  4. 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

  1. Step 1: Check content-type header

    The code checks if the request content type includes 'application/json' to decide parsing method.
  2. Step 2: Parse accordingly

    If JSON, it uses request.json(). Otherwise, it uses request.formData() and converts form entries to an object.
  3. Step 3: Return consistent JSON response

    Both branches return JSON stringified data, handling both content types correctly.
  4. Final Answer:

    Conditional parsing based on content-type header -> Option A
  5. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard