Home > database >  req.body() is getting empty while inserting data in MERN
req.body() is getting empty while inserting data in MERN

Time:10-31

I have MERN project where i have to simply put my form data in my database. All looking good but data is not inserting. while there is no error also.

I have done console.log(req.body). after i getting empty {}.

As i have tried so many previous question in stackoverflow but noe of them helps me

this is my screenshot of console of my browser

browser screenshot

Showing staus 201 but data is not going in my database

How to debug this error. I have tried all solution. Atleast tell me the possible reasons of this error. it will help me a lot. i am trying from full 1 day

userSchema

const userSchema = new mongoose.Schema({
    identity: {
            type: String,  
    },
    names: {
            type: String,
    },
   
    phone: { 
            type: String,  
    },
    email: {
            type: String,
    },
    city: {
            type: String,
    },
    address: {
            type: String,
    },
    subject: {
            type: String,    
    },
    classes: {
            type: String, 
    },
    message: {
            type: String,
    },
})

const USER = mongoose.model("USER", userSchema)

module.exports = USER

register.js(frontend)


const Register = () => {
  const [newUser, setNewUser] = useState({
    identity: "",
    names: "",
    phone: "",
    email: "",
    city: "",
    address: "",
    subject: "",
    classes: "",
    message: "",
  });



  const handleSubmit = (e) => {
    e.preventDefault();
    const formData = new FormData();
    formData.append("identity", newUser.identity);
    formData.append("names", newUser.names);
    formData.append("phone", newUser.phone);
    formData.append("email", newUser.email);
    formData.append("city", newUser.city);
    formData.append("address", newUser.address);
    formData.append("subject", newUser.subject);
    formData.append("classes", newUser.classes);
    formData.append("message", newUser.message);

    axios({
      method: "post",
      url: "/register",
      data: formData,
      headers: { "Content-Type": "application/json" },
    })
      .then((response) => {
        console.log(response);
      })
      .then((data) => {
        console.log(data);
      })
      .catch((error) => {
        if (error.response) {
          console.log(error.response.data);
        }
      });
  };

  const handleChange = (e) => {
    setNewUser({ ...newUser, [e.target.name]: e.target.value });
  };

  

  return (
    <>
      <div class="container register mt-5">
        <h1 class="well text-register shadow p-4 rounded-3">
          Join as{" "}
          <label class="student">
            [{" "}
            <img src="https://img.icons8.com/external-vitaliy-gorbachev-lineal-color-vitaly-gorbachev/60/000000/external-man-avatars-vitaliy-gorbachev-lineal-color-vitaly-gorbachev-12.png" />{" "}
            Parent/Student{" "}
            <img src="https://img.icons8.com/external-justicon-lineal-color-justicon/64/000000/external-student-back-to-school-justicon-lineal-color-justicon.png" />{" "}
            ]
          </label>
          <h1 class="well text-register down">
            <i class="fas fa-arrow-right"></i> Hey! If you are looking for right
            tutor near by your location. Don't worry you are at right place.{" "}
            <i class="fas fa-arrow-left"></i>
          </h1>
        </h1>

        <div class="col-lg-12 well rounded-3">
          <div class="row mt-5 ">
            <form onSubmit={handleSubmit}  method = "post" class="shadow p-5">
              <div class="col-sm-12">
                <div class="row">
                  <div class="col-sm-12 form-group">
                    <label>
                      {" "}
                      <i class="far fa-dot-circle"></i> Your Identity
                    </label>
                    <input
                    type="text"
                    placeholder="Write Student or Parent"
                    class="form-control"
                    name="identity"
                    id="identity"
                    value={newUser.identity}
                    onChange={handleChange}
                  />
                  </div>
                </div>
                <div class="form-group">
                  <label>
                    {" "}
                    <i class="far fa-dot-circle"></i> Name
                  </label>
                  <input
                    type="text"
                    placeholder="Enter Your Full Name Here.."
                    class="form-control"
                    name="names"
                    id="names"
                    value={newUser.names}
                    onChange={handleChange}
                  />
                </div>
                <div class="form-group">
                  <label>
                    {" "}
                    <i class="far fa-dot-circle"></i> Phone Number
                  </label>
                  <input
                    type="text"
                    placeholder="Enter Phone Number Here.."
                    class="form-control"
                    name="phone"
                    id="phone"
                    value={newUser.phone}
                    onChange={handleChange}
                  />
                </div>
                <div class="form-group">
                  <label>
                    {" "}
                    <i class="far fa-dot-circle"></i> Email Address
                  </label>
                  <input
                    type="text"
                    placeholder="Enter Email Address Here.."
                    class="form-control"
                    name="email"
                    id="email"
                    value={newUser.email}
                    onChange={handleChange}
                  />
                </div>
                <div class="row">
                  <div class="col-sm-6 form-group">
                    <label>
                      {" "}
                      <i class="far fa-dot-circle"></i> City
                    </label>
                    <input
                      type="text"
                      placeholder="Enter City Name Here.."
                      class="form-control"
                      name="city"
                      id="city"
                      value={newUser.city}
                      onChange={handleChange}
                    />
                  </div>
                  <div class="col-sm-6 form-group">
                    <label>
                      {" "}
                      <i class="far fa-dot-circle"></i> Address
                    </label>
                    <textarea
                      placeholder="Enter Address Here.."
                      rows="3"
                      class="form-control"
                      name="address"
                      id="address"
                      value={newUser.address}
                      onChange={handleChange}
                    ></textarea>
                  </div>
                </div>
                <div class="row">
                  <div class="col-sm-6 form-group">
                    <label>
                      {" "}
                      <i class="far fa-dot-circle"></i> Subject
                    </label>
                    <input
                      type="text"
                      placeholder="Enter Subject Here.."
                      class="form-control"
                      name="subject"
                      id="subject"
                      value={newUser.subject}
                      onChange={handleChange}
                    />
                  </div>
                  <div class="col-sm-6 form-group">
                    <label>
                      {" "}
                      <i class="far fa-dot-circle"></i>Student Class
                    </label>
                    <input
                      type="text"
                      placeholder="Enter Student Class"
                      class="form-control"
                      name="classes"
                      id="classes"
                      value={newUser.classes}
                      onChange={handleChange}
                    />
                  </div>
                </div>

                <div class="form-group">
                  <label>
                    {" "}
                    <i class="far fa-dot-circle"></i> Message
                  </label>
                  <textarea
                    placeholder="Enter Any message you have for us..."
                    rows="3"
                    class="form-control"
                    name="message"
                    id="message"
                    value={newUser.message}
                    onChange={handleChange}
                  ></textarea>
                </div>
                <button value="register" type="submit" class="btn btn-lg btn-info">
                  Submit
                </button>

              </div>
            </form>
          </div>

        </div>
      </div>
    </>
  );
};

auth.js


router.get("/", (req, res) => {
    res.send("hello, i am communicating with router");
})


router.post("/register", async (req, res) => {
    const { identity, names, phone, email, city, address, subject, classes, message } = req.body
    console.log(req.body)

    try {
    
            const user = new User({identity ,names,  phone,email,city,address, subject, classes, message })
            await user.save()
            res.status(201).json({ message: "user registered successfulluy" })
        
        
    } catch (err) {
        console.log(err)
    }

})


module.exports = router

app.js


const port = 5000
env.config({path: "../server/config.env"})
require("../server/db/conn")
app.use(cors());
app.use(express.json())
app.use(require("../server/router/Auth"))


app.listen(port, (err) => {
    if (err) {
        return console.error(err);
    }
    return console.log(`server is listening on ${port}`);
});

Please help. i have tried so many times!!

Thankyou!!!

CodePudding user response:

Modify Your HandleSubmit function, do not use formData to submit your data as application/json

Instead, just use your current React State

const handleSubmit = (e) => {
    e.preventDefault();
    
    axios({
      method: "post",
      url: "/register",
      data: JSON.stringify(newUser),
      headers: { "Content-Type": "application/json" },
    })
      .then((response) => {
        console.log(response);
      })
      .then((data) => {
        console.log(data);
      })
      .catch((error) => {
        if (error.response) {
          console.log(error.response.data);
        }
      });
  };
  • Related