Last active
November 1, 2023 16:55
-
-
Save loso-nd/31fc7fe27fc6f92ccae3c5d6cad162a5 to your computer and use it in GitHub Desktop.
Next.JS - React Error: when hitting api (POST 500 (Internal Server Error) )
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 'use client' | |
| import { useState } from 'react'; | |
| import { useSession } from 'next-auth/react'; | |
| import { useRouter } from 'next/navigation'; | |
| import EmployeeForm from '@src/components/EmployeeForm'; | |
| const CreateEmployee = () => { | |
| const router = useRouter(); | |
| const { data: session } = useSession(); | |
| const [submitting, setIsSubmitting] = useState(false); | |
| const [employee, setEmployee] = useState({ | |
| employeeId: "", | |
| username: "", | |
| name: "", | |
| jobTitle: "", | |
| hoursPerPayPeriod: "", | |
| hourlyRate: "", | |
| exemptFlag: "", | |
| note: "" | |
| // email: "", | |
| // fundId: "", | |
| // projectId: "", | |
| }); | |
| const createEmployee = async (e) => { | |
| e.preventDefault(); | |
| setIsSubmitting(true); //used as a loader | |
| try { | |
| const response = await fetch('/api/employee/new', { | |
| method: 'POST', | |
| body: JSON.stringify({ | |
| userId: session?.user.id, | |
| employeeId: employee.employeeId, | |
| username: employee.username, | |
| name: employee.name, | |
| jobTitle: employee.jobTitle, | |
| hoursPerPayPeriod: employee.hoursPerPayPeriod, | |
| hourlyRate: employee.hourlyRate, | |
| exemptFlag: employee.exemptFlag, | |
| note: employee.note | |
| }), | |
| }); | |
| if (response.ok) { | |
| console.log("Is this going back to our home page?") | |
| router.push("/"); | |
| } | |
| } catch (error) { | |
| console.log(error); | |
| } finally { | |
| setIsSubmitting(false); | |
| } | |
| } | |
| return ( | |
| <EmployeeForm | |
| type="Create" | |
| employee={employee} | |
| setEmployee={setEmployee} | |
| isSubmitting={submitting} | |
| handleSubmit={createEmployee} | |
| /> | |
| ) | |
| }; | |
| export default CreateEmployee; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { connectToDB } from "@src/utils/database"; | |
| import Employee from "@src/models/employee"; | |
| export const POST = async (request) => { | |
| //write data we passed into the api request | |
| const { userId, username, note } = await request.json(); | |
| try { | |
| //connect to the db each time it creates a new prompt and dies out | |
| await connectToDB(); | |
| //new model | |
| const newEmployee = new Employee({ | |
| creator: userId, | |
| username, | |
| note | |
| }); | |
| await newEmployee.save(); | |
| return new Response(JSON.stringify(newEmployee), { status: 201 }); | |
| } catch (error) { | |
| return new Response("Failed to create a new Employee", { status: 500 }); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| I am working on this app and getting a 500 internal server Error with one of my APIs | |
| ERROR Persistent: ( http://localhost:3000/api/employee/new) | |
| WORK as expected: ( http://localhost:3000/api/prompt/new) | |
| The strange part is that the first api works fine with no errors. I legit copied over the code for the api that work s and pasted it into the employee code by filling in the details accordingly I am still getting an the 500 server error. | |
| I am not able to figure out why one API is working and the other is not when the structure of the code is essentially the same aside from the purpose of the components themselves. | |
| There are similar posts however none leads to any resolution to my problem. | |
| Terminal Log Looks fine. See attached file below. | |
| `MongoDB connected | |
| - wait compiling /api/auth/[...nextauth]/route (client and server)... | |
| - event compiled successfully in 280 ms (500 modules) | |
| - wait compiling... | |
| - event compiled client and server successfully in 967 ms (628 modules) | |
| - wait compiling /api/auth/[...nextauth]/route (client and server)... | |
| - event compiled successfully in 147 ms (497 modules) | |
| - wait compiling... | |
| - event compiled client and server successfully in 1400 ms (889 modules) | |
| - wait compiling /api/employee/new/route (client and server)... | |
| - event compiled successfully in 378 ms (500 modules) | |
| MongoDB connected | |
| - wait compiling... | |
| - event compiled client and server successfully in 888 ms (628 modules) | |
| - wait compiling /api/auth/[...nextauth]/route (client and server)... | |
| - event compiled successfully in 583 ms (497 modules)` | |
| Browswer console: | |
| page.jsx:31 | |
| POST http://localhost:3000/api/employee/new 500 (Internal Server Error) | |
| createEmployee @ page.jsx:31 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { Schema, model, models } from "mongoose"; | |
| const EmployeeSchema = new Schema({ | |
| creator: { | |
| type: Schema.Types.ObjectId, // docoument in the db such as user type | |
| ref: 'User', //one to many relationship | |
| }, | |
| employeeId: { | |
| type: Number, | |
| required: [true, 'Employeee ID is requried.'], | |
| }, | |
| username: { | |
| type: String, | |
| required: [true, 'Username is required.'], | |
| }, | |
| name: { | |
| type: String, | |
| required: [true, 'Employee Name is requried.'], | |
| }, | |
| jobTitle: { | |
| type: String, | |
| required: [true, 'Job Title is required.'], | |
| }, | |
| hoursPerPayPeriod: { | |
| type: String, | |
| required: [true, 'Hours Per Pay Period is requried.'], | |
| }, | |
| hourlyRate: { | |
| type: String, | |
| required: [true, 'Hourly Rate is required.'], | |
| }, | |
| exemptFlag: { | |
| type: String, | |
| required: [true, 'Exempt Flag is requried.'], | |
| }, | |
| note: { | |
| type: String, | |
| required: [true, 'Notes is required. If not, enter N/A.'], | |
| } | |
| }); | |
| // get the prompt that already exist or create a new prompt | |
| const Employee = models.Employee || model('Employee', EmployeeSchema); | |
| export default Employee; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Link from "next/link"; | |
| const EmployeeForm = ({ type, employee, setEmployee, submitting, handleSubmit }) => { | |
| return ( | |
| <section className="w-full max-w-full flex-start flex-col"> | |
| <h1 className="head_text text-left"> | |
| <span className="blue_gradient"> {type} Employee </span> | |
| </h1> | |
| <p className="desc text-left max-w-md"> {type} and manage employee information. | |
| </p> | |
| <form | |
| onSubmit={handleSubmit} | |
| className="mt-10 w-full max-w-2xl flex flex-col gap-7 glassmorphism"> | |
| <label> | |
| <span className="font-satoshi font-semibold text-base text-grey-700"> | |
| Enter Employee Information Details Below | |
| </span> | |
| </label> | |
| <label> | |
| <span className="font-satoshi font-semibold text-base text-grey-700"> | |
| Employee ID: | |
| </span> | |
| <input | |
| value={employee.employeeId} | |
| onChange={(e) => setEmployee({ | |
| ...employee, | |
| employeeId: e.target.value | |
| })} | |
| placeholder="Employee Id Number" | |
| //required | |
| className="form_input" | |
| /> | |
| </label> | |
| <label> | |
| <span className="font-satoshi font-semibold text-base text-grey-700"> | |
| Username: | |
| </span> | |
| <input | |
| value={employee.username} | |
| onChange={(e) => setEmployee({ | |
| ...employee, | |
| username: e.target.value | |
| })} | |
| placeholder="Username" | |
| //required | |
| className="form_input" | |
| /> | |
| </label> | |
| <label> | |
| <span className="font-satoshi font-semibold text-base text-grey-700"> | |
| Employee Name: | |
| </span> | |
| <input | |
| value={employee.name} | |
| onChange={(e) => setEmployee({ | |
| ...employee, | |
| name: e.target.value | |
| })} | |
| placeholder="Name" | |
| //required | |
| className="form_input" | |
| /> | |
| </label> | |
| <label> | |
| <span className="font-satoshi font-semibold text-base text-grey-700"> | |
| Job Title: | |
| </span> | |
| <input | |
| value={employee.jobTitle} | |
| onChange={(e) => setEmployee({ | |
| ...employee, | |
| jobTitle: e.target.value | |
| })} | |
| placeholder="Job Title" | |
| //required | |
| className="form_input" | |
| /> | |
| </label> | |
| <label> | |
| <span className="font-satoshi font-semibold text-base text-grey-700"> | |
| Hours Per Pay Period: | |
| </span> | |
| <input | |
| value={employee.hoursPerPayPeriod} | |
| onChange={(e) => setEmployee({ | |
| ...employee, | |
| hoursPerPayPeriod: e.target.value | |
| })} | |
| placeholder="Hours Per Pay Period:" | |
| //required | |
| className="form_input" | |
| /> | |
| </label> | |
| <label> | |
| <span className="font-satoshi font-semibold text-base text-grey-700"> | |
| Hourly Rate: | |
| </span> | |
| <input | |
| value={employee.hourlyRate} | |
| onChange={(e) => setEmployee({ | |
| ...employee, | |
| hourlyRate: e.target.value | |
| })} | |
| placeholder="Hourly Rate:" | |
| //required | |
| className="form_input" | |
| /> | |
| </label> | |
| <label> | |
| <span className="font-satoshi font-semibold text-base text-grey-700"> | |
| Exempt Flag | |
| </span> | |
| <input | |
| value={employee.exemptFlag} | |
| onChange={(e) => setEmployee({ | |
| ...employee, | |
| exemptFlag: e.target.value | |
| })} | |
| placeholder="Exempt Flag" | |
| //required | |
| className="form_input" | |
| /> | |
| </label> | |
| <label> | |
| <span className="font-satoshi font-semibold text-base text-grey-700"> | |
| Enter Employee Information Details Below | |
| </span> | |
| <textarea | |
| value={employee.note} | |
| onChange={(e) => setEmployee({ | |
| ...employee, | |
| note: e.target.value | |
| })} | |
| placeholder="Write your note here..." | |
| //required | |
| className="form_textarea" | |
| /> | |
| </label> | |
| <div className="flex-end mx-3 mb-5 gap-4"> | |
| <Link href="/" className="text-gray-500 text-sm"> | |
| Cancel | |
| </Link> | |
| <button | |
| type="submit" | |
| disabled={submitting} | |
| className="px-5 py-1.5 text-sm bg-primary-orange rounded-full text-white" | |
| > | |
| {submitting ? `${type}...` : type} | |
| </button> | |
| </div> | |
| </form> | |
| </section> | |
| ); | |
| }; | |
| export default EmployeeForm; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment