Sending Data from Frontend to Backend in a MERN Stack Project

Photo by Luca Bravo on Unsplash

Sending Data from Frontend to Backend in a MERN Stack Project

When embarking on a MERN (MongoDB, Express.js, React.js, Node.js) stack project, beginners often encounter the challenge of sending data from the frontend to the backend. While this may seem daunting at first, it's actually a straightforward process that forms the backbone of many web applications.

  1. Frontend setup

Let's start with the frontend, typically built using React.js. Suppose you have a form where users input their details, such as name, email, and password. Here's how you can send this data to the backend:


const handleSubmit = async () => {
  const formData = {
    name: "John Doe",
    email: "john@example.com",
    password: "securepassword123",
  };

  try {
    const response = await fetch("/api/users", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(formData),
    });

    const data = await response.json();
    console.log("Response from backend:", data);
  } catch (error) {
    console.error("Error:", error);
  }
};

In this code snippet:

  • We construct a JavaScript object formData containing the user's details.

  • Using the fetch API, we send a POST request to an endpoint (/api/users) on our backend server.

  • We set the Content-Type header to application/json to indicate that we're sending JSON data.

  • The body of the request contains the serialized JSON representation of formData.

  1. Backend Handling

    Now, let's move to the backend, typically implemented with Node.js and Express.js. Here's how you can handle the incoming data

// Backend code example using Node.js and Express.js
// Route to handle incoming user data
app.post("/api/users", async (req, res) => {
  const { name, email, password } = req.body;

  // Here, you would typically save the data to a MongoDB database
  res.status(200).json({ message: "User data received and saved successfully!" });
});

In this backend code:

  • We define a route (/api/users) that listens for incoming POST requests.

  • We extract the name, email, and password from the request body using object destructuring.

  • Typically, you would perform database operations (e.g., save to MongoDB) using an ORM or ODM library such as Mongoose.

  1. MongoDB integration

    Ensure you have MongoDB set up and configured in your backend project. This involves creating a database and defining schemas to structure your data effectively.

This explanation provide a clear overview of the process, making it for beginner to grasp the concept involved in sending data from frontend to backend in MERN stack project