Welcome, Learn how to build a complete contact form for our Backend in our MERN app! This easy-to-follow tutorial covers everything from creating the form structure to handling data.
π Resources mentioned in our MERN Course & Don't forget to watch π
π MongoDB Course: https://youtu.be/rU9ZODw5yvU
1: We need to create a Contact Schema and Model
const { Schema, model } = require("mongoose");
const contactSchema = new Schema({ username: { type: String, required: true }, email: { type: String, required: true },
message: { type: String, required: true }, });
// create a new collections(Model)
const Contact = new model("Contact", contactSchema); module.exports = Contact;
2: We need to create the contact route.
const express = require("express");
const router = express.Router();
const contactForm = require("../controllers/contact-controller");
router.route("/contact").post(contactForm);
module.exports = router;
3: We need to define the logics of contact in our Contact-controller.js file
const Contact = require("../models/contact-model");
const contactForm = async (req, res) => {
try {
const response = req.body;
await Contact.create(response);
return res.status(200).json({ message: "message send successfully" });
} catch (error) {
console.error(error);
return res.status(500).json({ message: "message not delivered" });
}
};
module.exports = contactForm;
4: Add the contact route in our server.js file
require("dotenv").config();
const express = require("express");
const app = express();
const router = require("./routes/auth-route");
const connectDb = require("./utils/db");
const errorMiddleware = require("./middlewares/error-middleware");
const contactRoute = require("./routes/contact-route");
// to get the json data in express app.
app.use(express.json());
// Mount the Router: To use the router in your main Express app, you can "mount" it at a specific URL prefix
app.use("/api/auth", router);
app.use("/api/form", contactRoute);
app.use(errorMiddleware);
const PORT = 5000;
connectDb().then(() => {
app.listen(PORT, () => {
console.log(`server is running at port: ${PORT}`);
});
});
This is how it will looks like in our postman app.
