#Form post not working on build

4 messages · Page 1 of 1 (latest)

lapis fossil
#

export const prerender = false;

import axios from "axios";
import { validateEmail } from "@/utils/validateEmail";

const errors = { name: "", email: "", message: "" };
let successMessage = "";
if (Astro.request.method === "POST") {
try {
const data = await Astro.request.formData();
const name = (data.get("name") as string) || "";
const email = (data.get("email") as string) || "";
const message = (data.get("message") as string) || "";

if (name.trim().length < 1) {
  errors.name += "Por favor, introduce tu nombre. ";
}
if (!validateEmail(email)) {
  errors.email += "El correo electrónico no es válido. ";
}
if (message.trim().length < 10) {
  errors.message += "El mensaje debe tener al menos 10 caracteres. ";
}

const hasErrors = Object.values(errors).some((msg) => msg);
if (!hasErrors) {
  await axios.post("https://api.ztservices.es/send-email", {
    name,
    email,
    message,
  });

  successMessage = "Correo enviado correctamente.";
}

} catch (error) {
console.error("Error al procesar el formulario:", error);
}
}

<div class="bg-white dark:bg-[#121212] p-6 rounded-lg shadow-lg w-1/2 border">
<h2 class="text-2xl font-semibold mb-6">Formulario de Contacto</h2>
<form method="POST" class="space-y-4">
<div class="flex flex-col gap-2">
<label for="name" class="font-medium">Nombre</label>
<input type="text" id="name" name="name" class="border border-gray-300 rounded-md p-2 w-full dark:text-[#121212]" required />
{errors.name && <p class="text-red-600 text-sm">{errors.name}</p>}
</div>

<div class="flex flex-col gap-2">
  <label for="email" class="font-medium">Correo Electrónico</label>
  <input type="email" id="email" name="email" class="border border-gray-300 rounded-md p-2 w-full dark:text-[#121212]" required />
  {errors.email && <p class="text-red-600 text-sm">{errors.email}</p>}
</div>

<div class="flex flex-col gap-2">
  <label for="message" class="font-medium">Mensaje</label>
  <textarea id="message" name="message" rows="4" class="border border-gray-300 rounded-md p-2 w-full dark:text-[#121212]" required></textarea>
  {errors.message && <p class="text-red-600 text-sm">{errors.message}</p>}
</div>

<button type="submit" class="px-6 py-3 bg-white text-blue-600 font-bold rounded-full shadow-md hover:bg-blue-100 hover:shadow-lg transition duration-300">
  Enviar
</button>

</form>

{successMessage && <p class="text-green-600 text-sm mt-4">{successMessage}</p>}
</div>

this code doens't work when I put it on production. the parent component has this server:defer and my output is set to: "static"

dreamy skyBOT
#

Hi @lapis fossil. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the information provided in your question and the knowledge sources available, I can identify the issue and provide a solution. The problem you're experiencing is related to the configuration of your Astro project and how you're handling server-side rendering.

The main reasons your form post is not working in production are:

  1. Your output is set to "static", which means your entire site is being prerendered at build time.
  2. You're using export const prerender = false on the page, which conflicts with the static output setting.
  3. You're trying to handle POST requests in a static site, which is not possible without server-side rendering.

To fix this issue, you need to make the following changes:

  1. Enable server-side rendering by adding an adapter for your deployment platform. As mentioned in the On-demand rendering guide, you need to add an adapter integration for your server runtime.

  2. Change your output configuration from "static" to "server". This will allow your site to handle server-side rendering and process form submissions. You can do this in your astro.config.mjs file:

    export default defineConfig({
      output: 'server',
      // other configuration options...
    });
    
  3. Keep the export const prerender = false at the top of your page file. This ensures that the page is rendered on-demand and can handle POST requests.

By making these changes, your form should work correctly in production. The server will be able to process the POST requests and handle the form submissions as expected.

For more information on setting up server-side rendering and handling forms in Astro, you can refer to the following resources:

#

Remember that switching to server-side rendering will change how your site is built and deployed. Make sure to update your deployment process accordingly.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: