Building a Full-Stack E-Commerce Site with MERN Stack

 Building a Full-Stack E-Commerce Site with MERN Stack


Are you looking to build a full-stack e-commerce site from scratch? Look no further than the MERN stack! The MERN stack consists of MongoDB, Express, React, and Node.js and is a popular choice for building modern web applications.


In this tutorial, we will walk you through the steps of building a full-stack e-commerce site using the MERN stack. We will cover everything from setting up your development environment to deploying your application to the cloud.


Prerequisites

Before we begin, make sure you have the following installed on your machine:


Node.js (v10 or higher)

npm (v6 or higher)

MongoDB (v4 or higher)

Step 1: Setting up the Backend

The first step is to set up the backend of our e-commerce site using Node.js and Express. Follow the steps below to create a new Node.js project and install the necessary dependencies:


Create a new directory for your project and navigate to it in your terminal.

Initialize a new Node.js project by running npm init.

Install the necessary dependencies by running npm install express mongoose body-parser cors.

Now that we have set up our project and installed the necessary dependencies, we can start building our backend API. Create a new file called server.js in your project directory and paste in the following code:


javascript


const express = require('express');

const mongoose = require('mongoose');

const bodyParser = require('body-parser');

const cors = require('cors');


const app = express();


// Middleware

app.use(bodyParser.json());

app.use(cors());


// Connect to MongoDB

mongoose.connect('mongodb://localhost/ecommerce', {

  useNewUrlParser: true,

  useUnifiedTopology: true,

});


mongoose.connection.on('connected', () => {

  console.log('Connected to MongoDB');

});


mongoose.connection.on('error', (err) => {

  console.error(`Failed to connect to MongoDB: ${err}`);

});


// Routes

app.get('/', (req, res) => {

  res.send('Hello World');

});


// Start the server

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => {

  console.log(`Server started on port ${PORT}`);

});

This code sets up an Express server, connects to a local MongoDB database, and defines a single route that returns "Hello World". You can test that your server is running by running node server.js in your terminal and visiting http://localhost:5000 in your browser.


Step 2: Defining the Data Model

Next, we need to define the data model for our e-commerce site. In this example, we will define a simple data model for products. Create a new directory called models in your project directory and create a new file called Product.js in it. Paste in the following code:


javascript

Copy code

const mongoose = require('mongoose');


const ProductSchema = new mongoose.Schema({

  name: {

    type: String,

    required: true,

  },

  description: {

    type: String,

    required: true,

  },

  price: {

    type: Number,

    required: true,

  },

  image: {

    type: String,

    required: true,

  },

});


module.exports = mongoose.model('Product', ProductSchema);

This code defines a Product schema with name, description, price, and image fields. We will use this schema to create, read, update, and delete products in our MongoDB database.


Step 3: Creating the API Endpoints

Now that we have defined our data model, we can create the API endpoints for our





praveennanda124@gmail.com

continue

e-commerce site. Create a new directory called routes in your project directory and create a new file called products.js in it. Paste in the following code:


javascript


const express = require('express');

const router = express.Router();

const Product = require('../models/Product');


// Get all products

router.get('/', async (req, res) => {

  try {

    const products = await Product.find();

    res.json(products);

  } catch (err) {

    console.error(err);

    res.status(500).send('Server Error');

  }

});


// Get a single product

router.get('/:id', async (req, res) => {

  try {

    const product = await Product.findById(req.params.id);

    if (!product) return res.status(404).json({ msg: 'Product not found' });

    res.json(product);

  } catch (err) {

    console.error(err);

    res.status(500).send('Server Error');

  }

});


// Create a product

router.post('/', async (req, res) => {

  try {

    const product = new Product(req.body);

    await product.save();

    res.json(product);

  } catch (err) {

    console.error(err);

    res.status(500).send('Server Error');

  }

});


// Update a product

router.put('/:id', async (req, res) => {

  try {

    const product = await Product.findByIdAndUpdate(req.params.id, req.body, { new: true });

    if (!product) return res.status(404).json({ msg: 'Product not found' });

    res.json(product);

  } catch (err) {

    console.error(err);

    res.status(500).send('Server Error');

  }

});


// Delete a product

router.delete('/:id', async (req, res) => {

  try {

    const product = await Product.findByIdAndDelete(req.params.id);

    if (!product) return res.status(404).json({ msg: 'Product not found' });

    res.json({ msg: 'Product deleted' });

  } catch (err) {

    console.error(err);

    res.status(500).send('Server Error');

  }

});


module.exports = router;

This code defines API endpoints for getting all products, getting a single product by ID, creating a new product, updating an existing product, and deleting a product.


Step 4: Setting up the Frontend

Now that we have set up our backend API, we can start building the frontend of our e-commerce site using React. Follow the steps below to create a new React project and install the necessary dependencies:


Create a new directory for your project and navigate to it in your terminal.

Initialize a new React project by running npx create-react-app client.

Install the necessary dependencies by running npm install axios react-router-dom.

Now that we have set up our project and installed the necessary dependencies, we can start building our frontend UI. Open the src/App.js file in your project directory and replace its contents with the following code:


javascript


import React, { useState, useEffect } from 'react';

import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';

import axios from 'axios';

import Navbar from './components/Navbar';

import Products from './components/Products';

import Product from './components/Product';

import AddProduct from './components/AddProduct';


function App() {

  const [products, setProducts] = useState([]);


  useEffect(() => {

    const fetchProducts = async () => {

      const res = await axios.get('/api/products');

      setProducts(res.data);

    };

    fetchProducts();

  }, []);


  const addProduct = async (product) =>

{

const res = await axios.post('/api/products', product);

setProducts([...products, res.data]);

};


const updateProduct = async (id, updatedProduct) => {

const res = await axios.put(/api/products/${id}, updatedProduct);

setProducts(

products.map((product) =>

product._id === id ? { ...res.data } : product

)

);

};


const deleteProduct = async (id) => {

await axios.delete(/api/products/${id});

setProducts(products.filter((product) => product._id !== id));

};


return (

<Router>

<Navbar />

<Switch>

<Route exact path="/">

<Products products={products} deleteProduct={deleteProduct} />

</Route>

<Route exact path="/product/:id">

<Product products={products} updateProduct={updateProduct} />

</Route>

<Route exact path="/add-product">

<AddProduct addProduct={addProduct} />

</Route>

</Switch>

</Router>

);

}


export default App;


php



This code defines the routes for our application using the `react-router-dom` package. It also defines the state for our `products` array and sets up functions for adding, updating, and deleting products.


Next, create a new directory called `components` in your `src` directory and create the following components:


1. `Navbar.js`: This component will display a navigation bar at the top of our site. Paste in the following code:


```javascript

import React from 'react';

import { Link } from 'react-router-dom';


function Navbar() {

  return (

    <nav className="navbar">

      <Link to="/" className="navbar-brand">

        E-Commerce Site

      </Link>

      <ul className="navbar-nav">

        <li className="nav-item">

          <Link to="/" className="nav-link">

            Home

          </Link>

        </li>

        <li className="nav-item">

          <Link to="/add-product" className="nav-link">

            Add Product

          </Link>

        </li>

      </ul>

    </nav>

  );

}


export default Navbar;

This code defines a simple navigation bar with links to the home page and the add product page.


Products.js: This component will display a list of all products. Paste in the following code:


javascript


import React from 'react';

import { Link } from 'react-router-dom';


function Products({ products, deleteProduct }) {

  const handleDelete = async (id) => {

    if (window.confirm('Are you sure you want to delete this product?')) {

      deleteProduct(id);

    }

  };


  return (

    <div className="container">

      <h1>All Products</h1>

      <ul className="list-group">

        {products.map((product) => (

          <li className="list-group-item" key={product._id}>

            <Link to={`/product/${product._id}`}>{product.name}</Link>

            <button

              className="btn btn-danger btn-sm float-end"

              onClick={() => handleDelete(product._id)}

            >

              Delete

            </button>

          </li>

        ))}

      </ul>

    </div>

  );

}


export default Products;

This code defines a component that displays a list of all products with a button to delete each one. The deleteProduct function is passed down from the parent component (App) as a prop.


No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...