Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
I'm getting 500 (Internal Server Error)while submitting the form in nextjs.

import React from 'react';
import {useState} from "react";

export default function DigiContact() {
  const [name, setName] = useState('');
  const [phone, setPhone] = useState('');
  const [school, setSchool] = useState('');
  const [role, setRole] = useState('');
  const [message, setMessage] = useState('');

  const handleSubmit = async (e) => {
      e.preventDefault();

      let form = {
          name,
          phone,
          school,
          role,
          message
      }

      const rawResponse = await fetch('/api/submit', {
          method: 'POST',
          body: JSON.stringify(form),
          headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
          },
      });
      setMessage('')
      setPhone('')
      setName('')
      setSchool('')
      setRole('')
  }
  return (
    <section>
      <div>
        <div>
          <div>
            <div>
              
                <div>
                  <div>
                    <div>
                       
                       setName(e.target.value)} type="text" name="name" 
                       id="name"                        
                        className="form-control"
                        placeholder="Name"
                        required
                      />
                    </div>
                  </div>
                  <div>
                    <div>
                       
                        setPhone(e.target.value)} type="tel" 
                        name="phone" id="phone"          
                        className="form-control"
                        placeholder="Phone"
                        required
                      />
                    </div>
                  </div>
                  <div>
                    <div>
                      <input
 value="{school}" onchange="{e" ==""> 
                        setSchool(e.target.value)} id="school" 
                        name="school"
                        type="text"
                        className="form-control"
                        placeholder="School Name"
                        required
                      />
                    </div>
                  </div>
                  <div>
                     
                     setRole(e.target.value)} id="role" 
                     name="role"class="form-select mb-3" aria- 
                     label="Default select example" required >
                      Select Your Role at 
                       School
                      Owner
                      Principal
                      Teacher
                      Student
                      Parent
                    
                  </div>
                  <div>
                    <textarea
 value="{message}" onchange="{e" ==""> 
                      setMessage(e.target.value)} id="message"
                      rows="4"
                      className="w-100 form-control"
                      placeholder="Message.."
                    >
                  </div>
                  <div>
                    
                      Get in touch
                    
                  </div>
                </div>
              
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}


//Here is the api/submit file

import {google} from "googleapis";

export default async function handler(req,res){
    if (req.method !== 'POST') {
        return res.status(405).send({ message: 'Only POST requests allowed' })
    }

    const {name,phone,school,message} = req.body

    try {
        const auth = new google.auth.GoogleAuth({
            credentials: {
                client_email: process.env.GOOGLE_CLIENT_EMAIL,
                private_key: process.env.GOOGLE_PRIVATE_KEY?.replace(/\\n/g, '\n'),
                client_id: process.env.CLIENT_ID
            },
            scopes: [
                'https://www.googleapis.com/auth/drive',
                'https://www.googleapis.com/auth/drive.file',
                'https://www.googleapis.com/auth/spreadsheets'
            ],
        });

        const sheets = google.sheets({
            auth,
            version: 'v4'
        });

        const response = await sheets.spreadsheets.values.append({
            spreadsheetId: process.env.GOOGLE_SHEET_ID,
            range: 'Form!A1:D1',
            valueInputOption: 'USER_ENTERED',
            requestBody: {
                values: [
                    [name,phone,school,message]
                ],
            },
        });

        return res.status(201).json({
            data: response.data
        })
    }catch (e) {
        return res.status(500).send({message: e.message}) 
        console.error("An error occured",500)
    }

}


please help me 😭

What I have tried:

please help me 😭
Posted
Updated 18-Oct-22 13:04pm
v2
Comments
Richard MacCutchan 18-Oct-22 14:04pm    
Look at the exception and print its details.
Member 15627495 19-Oct-22 0:52am    
error 500 is a server sided crash.
by your information, the code nested in the try block is faulty.
it could be a syntax error ( a missing ";" ???)

after 'scope' array there is a "," alone ...

make more try/catch block to be more accurate ( for debug only )

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900