Build Forms With API Routes
This recipe shows you how to send form data to an API endpoint and handle that data.
PrerequisitesSection titled Prerequisites
RecipeSection titled Recipe
Create a form component using your UI framework. Each input should have a
nameattribute that describes the value of that input.
Be sure to include a
<input type="submit">element to submit the form.
POSTAPI endpoint that will receive the form data. Use
request.formData()to process it. Be sure to validate the form values before you use them.
This example sends a JSON object with a message back to the client.
Create a function that accepts a submit event, then pass it as a
submitevent handler to your form. In the function, call
preventDefaulton the event to override the browser’s default submission process.
Then, create a
FormDataobject and send it to your endpoint using