Complete the code to handle form submission in a Deno Fresh handler.
export const handler = async (req) => {
if (req.method === '[1]') {
const formData = await req.formData();
const name = formData.get('name');
return new Response(`Hello, ${name}!`);
}
return new Response('Method Not Allowed', { status: 405 });
};Form submissions usually use the POST method to send data to the server.
Complete the code to extract a field named 'email' from the form data in a Deno Fresh handler.
const formData = await req.formData(); const email = formData.[1]('email');
The formData.get() method retrieves the value of a form field by its name.
Fix the error in the code to correctly parse JSON data from a POST request in Deno.
export const handler = async (req) => {
if (req.method === 'POST') {
const data = await req.[1]();
return new Response(`Received: ${JSON.stringify(data)}`);
}
return new Response('Method Not Allowed', { status: 405 });
};To parse JSON from a request body, use req.json() which returns a parsed object.
Fill both blanks to create a form handler that reads 'username' and 'password' from form data and returns a JSON response.
export const handler = async (req) => {
if (req.method === '[1]') {
const formData = await req.[2]();
const username = formData.get('username');
const password = formData.get('password');
return new Response(JSON.stringify({ username, password }), { headers: { 'Content-Type': 'application/json' } });
}
return new Response('Method Not Allowed', { status: 405 });
};The handler must check for POST method and use req.formData() to read form fields.
Fill all three blanks to create a mutation handler that updates user data from JSON and returns a success message.
export const handler = async (req) => {
if (req.method === '[1]') {
const data = await req.[2]();
const userId = data.[3];
// Imagine updating user in database here
return new Response(`User ${userId} updated successfully.`);
}
return new Response('Method Not Allowed', { status: 405 });
};Use PUT method for updates, parse JSON with req.json(), and access the user ID with data.id.
