I'm working on a SvelteKit project where I need to send form data from a server endpoint to an external API (FormSubmit.co/ajax). I'm able to send the form data directly from the client-side (in a +page.svelte
file), but when I try to send the form data from a server endpoint (+page.server.ts
), it doesn't work. I also tried deploying my webapp to Vercel to check the problem but it keeps giving me the same error:
{ success: "false", message: "Make sure you open this page through a web server, FormSubmit will not work in pages browsed as HTML files."}
Here's the code I'm using in my +page.server.ts
file:
export const actions = { default: async ({ request }) => { const formData = await request.formData(); const formValues = Object.fromEntries(formData); ... const response = await fetch('https://formsubmit.co/ajax/your-formsubmit-id', { method: 'POST', headers: {'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify(formValues) }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); if (data.success === 'false') { throw new Error(data.message); } return { status: 200, body: { success: true, resultMessage: 'The message was sent correctly' } }; }};
And this is the form I'm using in my +page.svelte
page:
...<form action="#" method="POST" use:enhance={() => { isLoading = true; return async ({ update }) => { await update(); isLoading = false; }; }} class="mx-auto mt-10 max-w-xl sm:mt-15">...
I have tried reading the documentation, I have tried many times to send server side but it keeps giving the same problem even loading the project on Vercel, while if I try to do a simple fetch from +page.svelte
the email arrives successfully, however I would like it to be sent from +page.server.ts
, how to do it? Thanks a lot to everyone in advance!