Currenly I learning about MERN Stack and started new project about Student Management system only using CRUD operations.
Student data viewing parts(geting data from db) and delete student data work fine.. but adding new student data to db is not working. everytime submit data to db it give me bad request(400) error.
//this is my form component
import React, { useState } from 'react'
import '../customComponent/custom.css'
import {
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogFooter
} from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
function CustomeAlert() {
const [nic,setNic]=useState("");
const [fName,setLName]=useState("");
.....other values.....
const [err,setErr]=useState(null);
const [emptyFields,setEmptyFields]=useState([])
const submitHandler=async()=>{
const student={nic,fName,lName,dob,gender,phone,address,email,isActive};
const response=await fetch('http://localhost:4000/api/students/add/',{
method:'POST',
body: JSON.stringify(student),
headers:{
"Content-Type":"application/json",
}
})
const json=await response.json();
if(!response.ok){
setErr(json.error)
setEmptyFields(json.emptyFields)
}
if(response.ok){
setNic("")
setLName("")
setFName("")
.....
setIsActive(true)
setErr(null)
setEmptyFields([])
alert("Student Added Successfully!");
}
}
return (
<DialogContent className='DialogContent'>
<DialogHeader>
<DialogTitle>Add a New Student</DialogTitle>
</DialogHeader>
<form>
<div className="grid grid-cols-3 grid-rows-3 gap-8 w-full h-full">
<div className='flex items-center'>
<label htmlFor="nic" className='mr-3'>NIC: </label>
<Input id="nic" value={nic} onChange={e=>setNic(e.target.value)}/>
</div>
<div className='flex items-center'>
<label htmlFor="fname" className='mr-3'>Firstname: </label>
<Input id="fname" value={fName} onChange={e=>setFName(e.target.value)}/>
</div>
<div className='flex items-center'>
<label htmlFor="lname" className='mr-3'>Lastname: </label>
<Input id="lname" value={lName} onChange={e=>setLName(e.target.value)}/>
</div>
<div className='flex items-center'>
<label htmlFor="dob" className='mr-3'>birthDate: </label>
<input type='date' id="dob" className='w-[15rem] p-2 rounded-md border border-slate-200'
onChange={e=>setDob(e.target.value)}
/>
</div>
**.....other input fields....**
</div>
</form>
<DialogFooter>
<div className='text-red-500'>{err?err:""}</div>
<button className='w-[8rem] rounded-lg border-2 border-violet-700 h-[3rem] p-1 hover:text-white hover:bg-violet-400' type="reset">Clear</button>
<button className='w-[8rem] text-white rounded-lg bg-violet-700 h-[3rem] p-1' type="submit" onClick={submitHandler}>Submit</button>
</DialogFooter>
</DialogContent>
)
}
export default CustomeAlert
//backend
//student.js
router.post('/add', addNewStudent)
//studentController.js
const addNewStudent = async(req, res) => {
//catch data come from request body
const { studentNic, firstName, lastName, birthdate, gender, mobileNo, Address, email, isActive } = req.body
//create empty array for check empty request
let emptyFields = []
//if any field has empty push values to emptyField array
if (!studentNic) {
emptyFields.push('studentNic')
}
if (!firstName) {
emptyFields.push('firstName')
}
if (!lastName) {
emptyFields.push('lastName')
}
if (!birthdate) {
emptyFields.push('birthdate')
}
if (!gender) {
emptyFields.push('gender')
}
if (!mobileNo) {
emptyFields.push('mobileNo')
}
if (!Address) {
emptyFields.push('Address')
}
if (!email) {
emptyFields.push('email')
}
if (isActive == undefined) {
emptyFields.push('isActive')
}
//if array has data then show this error messege
if (emptyFields.length > 0) {
return res.status(400).json({ error: "Please fill in all the Field", emptyFields })
}
//add document to database
try {
// Convert birthdate to Date object
const parsedBirthdate = new Date(birthdate);
const student = await StudentModel.create({ studentNic, firstName, lastName, birthdate: parsedBirthdate, gender, mobileNo, Address, email, isActive })
res.status(200).json(student)
} catch (error) {
res.status(400).json({ error: error.message })
}
}
how can i fix this issue?
