与端点NextJS 13.2的表单连接

5lwkijsr  于 2023-08-04  发布在  其他
关注(0)|答案(1)|浏览(88)

我正在尝试连接此表单:

'use client'
import React, { useState } from 'react';
import Button from 'react-bootstrap/Button';
import Form from 'react-bootstrap/Form';

export const Formulario = () => {
  const [formData, setFormData] = useState({
    Company: '',
    Position: '',
    Email: '',
    NumberOfEmployees: '',
    Terms: false,
    Message: '',
  });

  const handleChange = (event) => {
    const { name, value, type, checked } = event.target;
    const fieldValue = type === 'checkbox' ? checked : value;
    setFormData((prevFormData) => ({
      ...prevFormData,
      [name]: fieldValue,
    }));
    console.log(`Field '${name}' updated to value: ${fieldValue}`);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log('Form data submitted:', formData);
    fetch('/api/SubmitForm', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(formData),
    })
      .then((response) => {
        if (response.ok) {
          return response.json();
        } else {
          throw new Error('Network response was not ok');
        }
      })
      .then((data) => {
        console.log('Form submission response:', data.message); 
      })
      .catch((error) => {
        console.error('Form submission error:', error);
        
      });
  };

  return (
    <div className="row white-font p-3 d-flex">
      <div className="col-10 mx-auto">
        <h5 className="text-center">Únete a la lista de espera</h5>
      </div>
      <div className="col-10 mx-auto">
        <Form noValidate onSubmit={handleSubmit}>
          <Form.Group className="">
            <Form.Label className="formlabel" column="sm">
              Empresa
            </Form.Label>
            <Form.Control
              className="formplaceholder"
              size="sm"
              type="text"
              placeholder="Nombre de tu Company"
              name="Company"
              value={formData.Company}
              onChange={handleChange}
            />
          </Form.Group>

          <Form.Group className="">
            <Form.Label className="formlabel" column="sm">
              Cargo
            </Form.Label>
            <Form.Control
              className="formplaceholder"
              size="sm"
              type="text"
              placeholder="Cargo actual en tu Company"
              name="Position"
              value={formData.Position}
              onChange={handleChange}
            />
          </Form.Group>

          <Form.Group className="">
            <Form.Label className="formlabel" column="sm">
              Mail corporativo
            </Form.Label>
            <Form.Control
              className="formplaceholder"
              size="sm"
              type="email"
              placeholder="Mail de trabajo"
              name="Email"
              value={formData.Email}
              onChange={handleChange}
            />
          </Form.Group>

          <Form.Group className="">
            <Form.Label className="formlabel" column="sm">
              Número de trabajadores en tu equipo
            </Form.Label>
            <Form.Control
              className="formplaceholder"
              size="sm"
              type="number"
              placeholder="¿Cuántos sois en tu equipo?"
              name="NumberOfEmployees"
              value={formData.NumberOfEmployees}
              onChange={handleChange}
            />
          </Form.Group>

          <Form.Group className="" >
            <Form.Label className="formlabel" column="sm">
              Déjanos un mensaje
            </Form.Label>
            <Form.Control
              className="formplaceholder"
              size="sm"
              as="textarea"
              rows={3}
              placeholder="¿Tienes algo que decirnos? ¡Deja un comentario aquí!"
              name="Message"
              value={formData.Message}
              onChange={handleChange}
              spellCheck="false" // Update "spellcheck" to "spellCheck"
            />

          </Form.Group>

          <Form.Group className="inline-checkbox p-1">
            <Form.Check
              required
              type="checkbox"
              name="Terms"
              onChange={handleChange}
              checked={formData.Terms}
              feedbackType="invalid"
              id="validationFormik0"
              className="formTerms"
            />
            <Form.Check.Label
              htmlFor="validationFormik0"
              data-bs-toggle="modal"
              data-bs-target="#ModalTerms"
              className="form-check-label formTerms p-1"
            >
              He leído y acepto la política de privacidad
            </Form.Check.Label>
          </Form.Group>

          <div className="d-grid gap-2">
            <Button className="Gradient-Button" size="sm" type="submit">
              ¡Quiero firmail!
            </Button>
          </div>
        </Form>
      </div>
    </div>
  );
};

export default Formulario;

字符串
这个端点:

import { sql } from '@vercel/postgres';
import { NextResponse } from 'next/server';

export async function POST(request, response) {
  console.log(request.body);
  const Company = request.Company;
  const Position = request.Position;
  const Email = request.Email;
  const NumberOfEmployees = request.NumberOfEmployees;
  const Message = request.Message;
  if (!Company || !Position || !Email || !NumberOfEmployees || !Message) {
    return NextResponse.json({ error: 'All form fields are required' }, { status: 400 });
  }

  try {
    
    await sql`
      INSERT INTO LeadForm (company, position, email, numberofemployees, message)
      VALUES (${Company}, ${Position}, ${Email}, ${NumberOfEmployees}, ${Message});
    `;

    return NextResponse.json({ message: 'Form data inserted successfully into the database' }, { status: 200 });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: 'Error while inserting form data into the database' }, { status: 500 });
  }
}


我总是收到一个400作为答案,正文为null,而前面的console.log请求正在正确运行表单的数据。
我是NextJS 13.2和Node端点的新手,也许这是一件愚蠢的事情,但我真的尝试了很多方法来解决这个问题,但都没有成功。
这可能与端点的权限或我做错的一些方法有关吗?
希望有人能帮我解决这个问题??

a1o7rhls

a1o7rhls1#

在app router中,你需要根据请求调用jaon函数

export async function POST(request, response) {
  const body = request.json();
  console.log(body);
...
}

字符串
结账-https://nextjs.org/docs/app/building-your-application/routing/router-handlers

相关问题