Un formulario HTML hace que el navegador se actualice o navegue a una nueva página. Para enviar datos de formulario a un endpoint de API en su lugar, debes interceptar el envío del formulario usando JavaScript.
Esta receta muestra como enviar datos de un formulario a un endpoint de API y manejar esos datos.
Crea un endpoint de API POST
en /api/feedback
que recibirá los datos del formulario. Usa request.formData()
para procesarlos. Asegúrate de validar los valores del formularios antes de utilizarlos.
Este ejemplo manda un objeto JSON con un mensaje de vuelta al cliente.
import type { APIRoute } from " astro " ;
export const POST : APIRoute = async ( { request } ) => {
const data = await request . formData () ;
const name = data . get ( " name " ) ;
const email = data . get ( " email " ) ;
const message = data . get ( " message " ) ;
// Valida los datos - probablemente querrás hacer más que esto
if ( ! name || ! email || ! message) {
message: " Faltan campos requeridos " ,
// Haz algo con los datos, luego devuelve una respuesta de éxito
Crea un componente de formulario usando tu framework UI. Cada entrada debe tener un atributo name
que describa el valor de esa entrada.
Asegúrate de incluir un elemento <button>
o <input type="submit">
para enviar el formulario.
export default function Form () {
< input type = " text " id = " name " name = " name " required />
< input type = " email " id = " email " name = " email " required />
< textarea id = " message " name = " message " required />
export default function Form () {
< input type = " text " id = " name " name = " name " required />
< input type = " email " id = " email " name = " email " required />
< textarea id = " message " name = " message " required />
export default function Form () {
< input type = " text " id = " name " name = " name " required />
< input type = " email " id = " email " name = " email " required />
< textarea id = " message " name = " message " required />
< input type = " text " id = " name " name = " name " required />
< input type = " email " id = " email " name = " email " required />
< textarea id = " message " name = " message " required />
< input type = " text " id = " name " name = " name " required />
< input type = " email " id = " email " name = " email " required />
< textarea id = " message " name = " message " required / >
Crea una función que acepte un evento de envío, luego pásala como un controlador submit
a tu formulario.
En la función:
Llama a preventDefault()
en el evento para anular el proceso de envío predeterminado del navegador.
Crea un objeto FormData
y envíalo a tu endpoint como una solicitud POST
usando fetch()
.
import { useState } from " preact/hooks " ;
export default function Form () {
const [ responseMessage , setResponseMessage ] = useState ( "" );
async function submit ( e : SubmitEvent ) {
const formData = new FormData (e . target as HTMLFormElement );
const response = await fetch ( " /api/feedback " , {
const data = await response . json ();
setResponseMessage (data . message );
< input type = " text " id = " name " name = " name " required />
< input type = " email " id = " email " name = " email " required />
< textarea id = " message " name = " message " required />
{ responseMessage && < p > { responseMessage } </ p > }
import { FormEvent, useState } from " react " ;
export default function Form () {
const [ responseMessage , setResponseMessage ] = useState ( "" );
async function submit ( e : FormEvent < HTMLFormElement > ) {
const formData = new FormData (e . target as HTMLFormElement );
const response = await fetch ( " /api/feedback " , {
const data = await response . json ();
setResponseMessage (data . message );
< input type = " text " id = " name " name = " name " autoComplete = " name " required />
< input type = " email " id = " email " name = " email " autoComplete = " email " required />
< label htmlFor = " message " >
< textarea id = " message " name = " message " autoComplete = " off " required />
{ responseMessage && < p > { responseMessage } </ p > }
import { createSignal, createResource, Suspense } from " solid-js " ;
async function postFormData ( formData : FormData ) {
const response = await fetch ( " /api/feedback " , {
const data = await response . json ();
export default function Form () {
const [ formData , setFormData ] = createSignal < FormData > ();
const [ response ] = createResource ( formData , postFormData);
function submit ( e : SubmitEvent ) {
setFormData ( new FormData (e . target as HTMLFormElement ));
< input type = " text " id = " name " name = " name " required />
< input type = " email " id = " email " name = " email " required />
< textarea id = " message " name = " message " required />
< Suspense > { response () && < p > { response () . message } </ p > } </ Suspense >
let responseMessage : string ;
async function submit ( e : SubmitEvent ) {
const formData = new FormData (e . currentTarget as HTMLFormElement );
const response = await fetch ( " /api/feedback " , {
const data = await response . json ();
responseMessage = data . message ;
< form on :submit= { submit } >
< input type = " text " id = " name " name = " name " required />
< input type = " email " id = " email " name = " email " required />
< textarea id = " message " name = " message " required />
import { ref } from " vue " ;
const responseMessage = ref < string > ();
async function submit ( e : Event ) {
const formData = new FormData (e . currentTarget as HTMLFormElement );
const response = await fetch ( " /api/feedback " , {
const data = await response . json ();
responseMessage . value = data . message ;
< input type = " text " id = " name " name = " name " required />
< input type = " email " id = " email " name = " email " required />
< textarea id = " message " name = " message " required / >
< p v-if = " responseMessage " > {{ responseMessage }} </ p >
Importa y usa el componente <FeedbackForm />
en la página. Asegúrate de utilizar una directiva client:*
para garantizar que la lógica del formulario se hidrate cuando lo deseas.
import FeedbackForm from " ../components/FeedbackForm "
< FeedbackForm client:load />
import FeedbackForm from " ../components/FeedbackForm "
< FeedbackForm client:load />
import FeedbackForm from " ../components/FeedbackForm "
< FeedbackForm client:load />
import FeedbackForm from " ../components/FeedbackForm.svelte "
< FeedbackForm client:load />
import FeedbackForm from " ../components/FeedbackForm.vue "
< FeedbackForm client:load />
Recipes