amine.official
01/13/2024, 1:03 PMMY_URL.com/api/submit
page.
I am using Astro (SSG) (V 3.3.4) with Pages (V 8.0.0) and Wrangler (V 3.22.4)
What a want to do?
- I want to create a simple form. When i submit the form my cloudflare pages function send me an email (with Resend.com api)
What is the problem?
- Everything is working, when i submit my form it send my an email but i don't want to be redirect from the MY_URL.com/contact
to MY_URL.com/api/submit
- I have this problem in dev (local) and in deployment
I don't understand why i have this redirection (Step 2 in the screenshoot)
My code:
pages/contact.astro
js
---
import Layout from '../layouts/Layout.astro';
---
<Layout title='Contact'>
<form method="POST" action="/api/submit">
<input type="text" name="name" pattern="[A-Za-z]+" required />
<input type="email" name="email" required />
<button type="submit">Submit</button>
</form>
</Layout>
functions/api/submit.js
js
export async function onRequestPost(context) {
return await submitHandler(context);
}
async function submitHandler(context) {
const body = await context.request.formData();
const { name, email} = Object.fromEntries(body);
return fetch('https://api.resend.com/emails', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${RESEND_API_KEY}`,
},
body: JSON.stringify({
from: `${MY_EMAIL}`,
to: [`${email}`],
subject: 'hello world',
html: `${name}`,
}),
});
}
amine.official
01/13/2024, 1:09 PMbefus
01/14/2024, 11:10 PMamine.official
01/15/2024, 8:30 AM/functions/api/submit.js
but it was not, it's an Astro problem. Because i was using SSG, if i was using SSR i probably didn't got this redirect.
In SSR mode, Astro pages can both display and handle forms. In this recipe, you’ll use a standard HTML form to submit data to the server. Your frontmatter script will handle the data on the server, sending no JavaScript to the client.
[Source: Astro doc](https://docs.astro.build/en/recipes/build-forms/)
But i don't want use SSR just for a contact/newsletter form. I think it's possible to do that with SSG, i didn't change anything in functions/api/submit.js
file but i did some modifications on my form pages/contact.astro
It's look like that:
jsx
---
import Layout from '../layouts/Layout.astro';
---
<Layout title='Contact'>
<form id="contact">
<input type="text" name="name" pattern="[A-Za-z]+" required />
<input type="email" name="email" required />
<button type="submit">Submit</button>
</form>
</Layout>
<script is:inline>
const pushForm = async (event) => {
event.preventDefault()
try {
const data = new FormData(event.target);
fetch(`/api/submit`, {
body: data, method: 'post'
})
} catch (error) {
if (error instanceof Error) {
console.error(error.message);
}
}
}
document.getElementById("contact").addEventListener("submit", pushForm);
</script>
I don't have redirection or page refresh with this code but i don't know if it's the right way to do it or not