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) {
return new Response (
JSON . stringify ( {
message: " Faltan campos requeridos " ,
} ) ,
{ status: 400 }
) ;
}
// Haz algo con los datos, luego devuelve una respuesta de éxito
return new Response (
JSON . stringify ( {
message: " ¡Éxito! "
} ) ,
{ status: 200 }
) ;
} ;
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 () {
return (
< form >
< label >
Nombre
< input type = " text " id = " name " name = " name " required />
</ label >
< label >
Correo electrónico
< input type = " email " id = " email " name = " email " required />
</ label >
< label >
Mensaje
< textarea id = " message " name = " message " required />
</ label >
< button > Enviar </ button >
</ form >
);
}
export default function Form () {
return (
< form >
< label >
Nombre
< input type = " text " id = " name " name = " name " required />
</ label >
< label >
Correo electrónico
< input type = " email " id = " email " name = " email " required />
</ label >
< label >
Mensaje
< textarea id = " message " name = " message " required />
</ label >
< button > Enviar </ button >
</ form >
);
}
export default function Form () {
return (
< form >
< label >
Nombre
< input type = " text " id = " name " name = " name " required />
</ label >
< label >
Correo electrónico
< input type = " email " id = " email " name = " email " required />
</ label >
< label >
Mensaje
< textarea id = " message " name = " message " required />
</ label >
< button > Enviar </ button >
</ form >
);
}
< form >
< label >
Nombre
< input type = " text " id = " name " name = " name " required />
</ label >
< label >
Correo electrónico
< input type = " email " id = " email " name = " email " required />
</ label >
< label >
Mensaje
< textarea id = " message " name = " message " required />
</ label >
< button > Enviar </ button >
</ form >
< template >
< form >
< label >
Nombre
< input type = " text " id = " name " name = " name " required />
</ label >
< label >
Correo electrónico
< input type = " email " id = " email " name = " email " required />
</ label >
< label >
Mensaje
< textarea id = " message " name = " message " required / >
</ label >
< button > Enviar </ button >
</ form >
</ template >
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 ) {
e . preventDefault ();
const formData = new FormData (e . target as HTMLFormElement );
const response = await fetch ( " /api/feedback " , {
method: " POST " ,
body: formData ,
} );
const data = await response . json ();
if (data . message ) {
setResponseMessage (data . message );
}
}
return (
< form onSubmit = { submit } >
< label >
Nombre
< input type = " text " id = " name " name = " name " required />
</ label >
< label >
Correo electrónico
< input type = " email " id = " email " name = " email " required />
</ label >
< label >
Mensaje
< textarea id = " message " name = " message " required />
</ label >
< button > Enviar </ button >
{ responseMessage && < p > { responseMessage } </ p > }
</ form >
);
}
import { FormEvent, useState } from " react " ;
export default function Form () {
const [ responseMessage , setResponseMessage ] = useState ( "" );
async function submit ( e : FormEvent < HTMLFormElement > ) {
e . preventDefault ();
const formData = new FormData (e . target as HTMLFormElement );
const response = await fetch ( " /api/feedback " , {
method: " POST " ,
body: formData ,
} );
const data = await response . json ();
if (data . message ) {
setResponseMessage (data . message );
}
}
return (
< form onSubmit = { submit } >
< label htmlFor = " name " >
Nombre
< input type = " text " id = " name " name = " name " autoComplete = " name " required />
</ label >
< label htmlFor = " email " >
Correo electrónico
< input type = " email " id = " email " name = " email " autoComplete = " email " required />
</ label >
< label htmlFor = " message " >
Mensaje
< textarea id = " message " name = " message " autoComplete = " off " required />
</ label >
< button > Enviar </ button >
{ responseMessage && < p > { responseMessage } </ p > }
</ form >
);
}
import { createSignal, createResource, Suspense } from " solid-js " ;
async function postFormData ( formData : FormData ) {
const response = await fetch ( " /api/feedback " , {
method: " POST " ,
body: formData ,
} );
const data = await response . json ();
return data;
}
export default function Form () {
const [ formData , setFormData ] = createSignal < FormData > ();
const [ response ] = createResource ( formData , postFormData);
function submit ( e : SubmitEvent ) {
e . preventDefault ();
setFormData ( new FormData (e . target as HTMLFormElement ));
}
return (
< form onSubmit = { submit } >
< label >
Nombre
< input type = " text " id = " name " name = " name " required />
</ label >
< label >
Correo electrónico
< input type = " email " id = " email " name = " email " required />
</ label >
< label >
Mensaje
< textarea id = " message " name = " message " required />
</ label >
< button > Enviar </ button >
< Suspense > { response () && < p > { response () . message } </ p > } </ Suspense >
</ form >
);
}
< script lang = " ts " >
let responseMessage : string ;
async function submit ( e : SubmitEvent ) {
e . preventDefault ();
const formData = new FormData (e . currentTarget as HTMLFormElement );
const response = await fetch ( " /api/feedback " , {
method: " POST " ,
body: formData ,
} );
const data = await response . json ();
responseMessage = data . message ;
}
</ script >
< form on :submit= { submit } >
< label >
Nombre
< input type = " text " id = " name " name = " name " required />
</ label >
< label >
Correo electrónico
< input type = " email " id = " email " name = " email " required />
</ label >
< label >
Mensaje
< textarea id = " message " name = " message " required />
</ label >
< button > Enviar </ button >
{# if responseMessage}
< p > { responseMessage } </ p >
{/ if }
</ form >
< script setup lang = " ts " >
import { ref } from " vue " ;
const responseMessage = ref < string > ();
async function submit ( e : Event ) {
e . preventDefault ();
const formData = new FormData (e . currentTarget as HTMLFormElement );
const response = await fetch ( " /api/feedback " , {
method: " POST " ,
body: formData ,
} );
const data = await response . json ();
responseMessage . value = data . message ;
}
</ script >
< template >
< form @submit = " submit " >
< label >
Nombre
< input type = " text " id = " name " name = " name " required />
</ label >
< label >
Correo electrónico
< input type = " email " id = " email " name = " email " required />
</ label >
< label >
Mensaje
< textarea id = " message " name = " message " required / >
</ label >
< button > Enviar </ button >
< p v-if = " responseMessage " > {{ responseMessage }} </ p >
</ form >
</ template >
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