Best Cosmetic Hospitals Near You

Compare top cosmetic hospitals, aesthetic clinics & beauty treatments by city.

Trusted • Verified • Best-in-Class Care

Explore Best Hospitals

Comprehensive Guide to Building a Full-Stack CRUD App with React, Express, and MongoDB

Here’s a comprehensive guide to creating a CRUD (Create, Read, Update, Delete) application using Express.js, React.js, and MongoDB. This guide will cover the backend setup (with Express and MongoDB) and the frontend setup (with React). The full-stack application will allow you to perform CRUD operations

1. Backend Setup (Express.js and MongoDB)


Step 1: Initialize the Node.js Project

  1. Open your terminal or command prompt, and navigate to the folder where you want to create the project: mkdir express-react-mongo-crud cd express-react-mongo-crud
  2. Initialize a new Node.js project: npm init -y

Step 2: Install Dependencies

Install the necessary backend dependencies using npm:

npm install express mongoose cors dotenv
  • express: Web framework for Node.js.
  • mongoose: MongoDB ORM to interact with MongoDB.
  • cors: To enable cross-origin resource sharing.
  • dotenv: To manage environment variables (e.g., MongoDB URI).

Step 3: Set Up Express Server

  1. Create the server.js file in the root directory of the project: touch server.js
  2. Add the following code to server.js to set up Express and MongoDB:
const express = require('express'); const mongoose = require('mongoose'); const cors = require('cors'); require('dotenv').config(); // For environment variables // Initialize the app const app = express(); // Set up middleware app.use(cors()); app.use(express.json()); // For parsing JSON data // MongoDB connection mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('MongoDB connected')) .catch((err) => console.log('MongoDB connection error: ' + err)); // Define routes const itemRoutes = require('./routes/items'); app.use('/api/items', itemRoutes); // Basic route to check server app.get('/', (req, res) => { res.send('Hello World'); }); // Start the server const port = process.env.PORT || 5000; app.listen(port, () => { console.log(`Server running on port: ${port}`); });
  1. Create a .env file to store your MongoDB URI: touch .env
  2. Add the following MongoDB connection string to the .env file (adjust for your MongoDB instance): MONGO_URI=mongodb://localhost:27017/crud_app

Step 4: Create MongoDB Model

  1. Create a models folder to store the database models: mkdir models
  2. Create a Item.js file inside the models folder: touch models/Item.js
  3. Add the following code to define the Item model in Item.js: const mongoose = require('mongoose'); const itemSchema = new mongoose.Schema({ name: { type: String, required: true }, description: { type: String, required: true }, }); module.exports = mongoose.model('Item', itemSchema);

Step 5: Create Routes for CRUD Operations

  1. Create a routes folder to store the route definitions: mkdir routes
  2. Create a items.js file inside the routes folder: touch routes/items.js
  3. Add the following CRUD routes to items.js:
 const express = require('express'); const Item = require('../models/Item'); const router = express.Router(); // Create a new item router.post('/', async (req, res) => { const { name, description } = req.body; try { const newItem = new Item({ name, description }); await newItem.save(); res.status(201).json(newItem); } catch (error) { res.status(500).json({ error: error.message }); } }); // Get all items router.get('/', async (req, res) => { try { const items = await Item.find(); res.status(200).json(items); } catch (error) { res.status(500).json({ error: error.message }); } }); // Get a single item router.get('/:id', async (req, res) => { try { const item = await Item.findById(req.params.id); if (!item) return res.status(404).json({ error: 'Item not found' }); res.status(200).json(item); } catch (error) { res.status(500).json({ error: error.message }); } }); // Update an item router.put('/:id', async (req, res) => { try { const updatedItem = await Item.findByIdAndUpdate(req.params.id, req.body, { new: true }); if (!updatedItem) return res.status(404).json({ error: 'Item not found' }); res.status(200).json(updatedItem); } catch (error) { res.status(500).json({ error: error.message }); } }); // Delete an item router.delete('/:id', async (req, res) => { try { const deletedItem = await Item.findByIdAndDelete(req.params.id); if (!deletedItem) return res.status(404).json({ error: 'Item not found' }); res.status(200).json({ message: 'Item deleted' }); } catch (error) { res.status(500).json({ error: error.message }); } }); module.exports = router;
  1. Now your backend is set up to handle CRUD operations for items.

2. Frontend Setup (React.js)


Step 1: Create the React App

  1. Open a new terminal, navigate to the root folder of your project, and create a new React app inside the client folder: npx create-react-app client cd client
  2. Install Axios to handle HTTP requests: npm install axios

Step 2: Create Items.js Component

  1. Inside the src folder of your React app (client/src), create a new file named Items.js: touch src/Items.js
  2. Add the following code to Items.js for fetching and displaying items:
 import React, { useState, useEffect } from 'react'; import axios from 'axios'; const Items = () => { const [items, setItems] = useState([]); const [name, setName] = useState(''); const [description, setDescription] = useState(''); const [editingItem, setEditingItem] = useState(null); // Fetch all items from backend useEffect(() => { axios.get('http://localhost:5000/api/items') .then(response => setItems(response.data)) .catch(error => console.log(error)); }, []); // Add a new item const handleAddItem = () => { axios.post('http://localhost:5000/api/items', { name, description }) .then(response => { setItems([...items, response.data]); setName(''); setDescription(''); }) .catch(error => console.log(error)); }; // Handle editing an item const handleEditItem = (item) => { setEditingItem(item); setName(item.name); setDescription(item.description); }; // Update an item const handleUpdateItem = () => { axios.put(`http://localhost:5000/api/items/${editingItem._id}`, { name, description }) .then(response => { setItems(items.map(item => (item._id === response.data._id ? response.data : item))); setEditingItem(null); setName(''); setDescription(''); }) .catch(error => console.log(error)); }; // Delete an item const handleDeleteItem = (id) => { axios.delete(`http://localhost:5000/api/items/${id}`) .then(() => setItems(items.filter(item => item._id !== id))) .catch(error => console.log(error)); }; return ( <div> <h1>CRUD Application</h1> <input type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="Item name" /> <input type="text" value={description} onChange={(e) => setDescription(e.target.value)} placeholder="Item description" /> <button onClick={editingItem ? handleUpdateItem : handleAddItem}> {editingItem ? 'Update Item' : 'Add Item'} </button> <ul> {items.map(item => ( <li key={item._id}> {item.name} - {item.description} <button onClick={() => handleEditItem(item)}>Edit</button> <button onClick={() => handleDeleteItem(item._id)}>Delete</button> </li> ))} </ul> </div> ); }; export default Items;

    Step 3: Update App.js to Render Items Component

    1. Open src/App.js and update it to include the Items component: import React from 'react'; import './App.css'; import Items from './Items'; function App() { return ( <div className="App"> <Items /> </div> ); } export default App;

    Step 4: Run React and Express Servers

    1. In your client folder, run the React development server: npm start
    2. In the root folder, run the Express backend server: node server.js

    OutPut:


    Summary

    • Backend: Set up Express and MongoDB to handle CRUD operations via API routes (/api/items).
    • Frontend: Created a React component (Items.js) to interact with the backend, using Axios for HTTP requests to perform CRUD actions (add, update, delete, fetch items).
    • Running both servers: Use npm start for the React frontend and node server.js for the backend server.

    You now have a full-stack CRUD application with Express, React, and MongoDB. Let me know if you need further help or clarification!

    Best Cardiac Hospitals Near You

    Discover top heart hospitals, cardiology centers & cardiac care services by city.

    Advanced Heart Care • Trusted Hospitals • Expert Teams

    View Best Hospitals
    <p data-start="140" data-end="435">I’m Abhishek, a DevOps, SRE, DevSecOps, and Cloud expert with a passion for sharing knowledge and real-world experiences. I’ve had the opportunity to work with <a class="decorated-link" href="https://www.cotocus.com/" target="_new" rel="noopener" data-start="300" data-end="335">Cotocus</a> and continue to contribute to multiple platforms where I share insights across different domains:</p> <ul data-start="437" data-end="922"> <li data-start="437" data-end="514"> <p data-start="439" data-end="514"><a class="decorated-link" href="https://www.devopsschool.com/" target="_new" rel="noopener" data-start="439" data-end="485">DevOps School</a> – Tech blogs and tutorials</p> </li> <li data-start="515" data-end="599"> <p data-start="517" data-end="599"><a class="decorated-link" href="https://www.holidaylandmark.com/" target="_new" rel="noopener" data-start="517" data-end="569">Holiday Landmark</a> – Travel stories and guides</p> </li> <li data-start="600" data-end="684"> <p data-start="602" data-end="684"><a class="decorated-link" href="https://www.stocksmantra.in/" target="_new" rel="noopener" data-start="602" data-end="647">Stocks Mantra</a> – Stock market strategies and tips</p> </li> <li data-start="685" data-end="764"> <p data-start="687" data-end="764"><a class="decorated-link" href="https://www.mymedicplus.com/" target="_new" rel="noopener" data-start="687" data-end="732">My Medic Plus</a> – Health and fitness guidance</p> </li> <li data-start="765" data-end="841"> <p data-start="767" data-end="841"><a class="decorated-link" href="https://www.truereviewnow.com/" target="_new" rel="noopener" data-start="767" data-end="814">TrueReviewNow</a> – Honest product reviews</p> </li> <li data-start="842" data-end="922"> <p data-start="844" data-end="922"><a class="decorated-link" href="https://www.wizbrand.com/" target="_new" rel="noopener" data-start="844" data-end="881">Wizbrand</a> – SEO and digital tools for businesses</p> </li> </ul> <p data-start="924" data-end="1021">I’m also exploring the fascinating world of <a class="decorated-link" href="https://www.quantumuting.com/" target="_new" rel="noopener" data-start="968" data-end="1018">Quantum Computing</a>.</p>

    Related Posts

    Bridging Dev and Ops With Consulting Best Practices

    Introduction Picture a mid-sized software engineering organization. The development team has spent the last three months building a new customer-facing analytics service. The code is polished, the…

    Read More

    Discovering Your Community: The Everyday Guide to Sourcing Nearby Goods and Services

    Households constantly look for merchandise and professional assistance right in their immediate districts. While global shipping networks frequently command widespread attention, countless individuals still appreciate the instant…

    Read More

    Finding Clarity in Cancer Care: A Practical Guide for Patients and Families

    Receiving a malignant diagnosis instantly disrupts a family’s normal rhythm, bringing immense emotional pressure right alongside urgent healthcare choices. Because contemporary oncology depends heavily on specialized clinical…

    Read More

    Choosing the Right Care Center: A Practical Approach to Neurosurgical Treatment and Hospital Selection

    Facing a medical condition or a recommended treatment involving the brain, spine, or central nervous system can be a profound turning point. Because procedures targeting delicate neural…

    Read More

    The Kitchen Table Archive: Recovering Family Recipes and Culinary Roots

    Cooking has always served as an unspoken chronicle of human life. Every meal carries an invisible narrative, linking us to previous eras through familiar aromas and grounding…

    Read More

    How DevOps Consulting Enhances Customer Experience

    A customer adds items to a shopping cart, proceeds to checkout, and clicks submit. The screen freezes, spins for twenty seconds, and returns a blank page or…

    Read More
    0 0 votes
    Article Rating
    Subscribe
    Notify of
    guest
    0 Comments
    Oldest
    Newest Most Voted
    0
    Would love your thoughts, please comment.x
    ()
    x