,

Demonstration of a MERN Stack E-commerce Website for Computer Hardware

Posted by


In this tutorial, we will build an E-commerce website for computer hardware using the MERN stack (MongoDB, Express.js, React.js, Node.js). This project will demonstrate how to create a full-stack web application that allows users to buy computer hardware products online.

To start with, make sure you have Node.js and MongoDB installed on your local machine. If not, you can download and install Node.js from https://nodejs.org/en/ and MongoDB from https://www.mongodb.com/try/download/community.

Once you have Node.js and MongoDB installed, let’s create a new project folder and navigate into it using the command line. From the terminal, run the following command to create a new MERN stack project:

npx create-react-app computer-hardware-store

This command will create a new React project with the name "computer-hardware-store". Once the project is created, navigate into the project folder by running:

cd computer-hardware-store

Next, let’s add Express.js server to the project. Create a new folder called "server" inside the project directory and navigate into it. Inside the server folder, run the following command to initialize a new Node.js project:

npm init -y

Now, let’s install the necessary dependencies for the server. Run the following command to install Express.js and other required packages:

npm install express body-parser mongoose cors

Next, let’s create an Express.js server file. Create a new file called "server.js" inside the server folder and add the following code:

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');

const app = express();
const PORT = 5000;

app.use(cors());
app.use(bodyParser.json());

mongoose.connect('mongodb://localhost/computer-hardware-store', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

This code sets up an Express.js server with CORS support and connects to a local MongoDB database named "computer-hardware-store". Now, let’s create models for the computer hardware products.

Create a new folder called "models" inside the server folder. Inside the models folder, create a new file called "Product.js" and add the following code:

const mongoose = require('mongoose');

const productSchema = new mongoose.Schema({
  name: String,
  description: String,
  price: Number,
  image: String,
});

const Product = mongoose.model('Product', productSchema);

module.exports = Product;

This code defines a Mongoose schema for computer hardware products with fields for name, description, price, and image. Now, let’s create routes for CRUD operations on products.

Create a new folder called "routes" inside the server folder. Inside the routes folder, create a new file called "productRoutes.js" and add the following code:

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

const router = express.Router();

router.get('/', async (req, res) => {
  try {
    const products = await Product.find();
    res.json(products);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

router.post('/', async (req, res) => {
  const product = new Product(req.body);

  try {
    await product.save();
    res.status(201).json(product);
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

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

  try {
    const product = await Product.findById(id);
    if (!product) {
      res.status(404).json({ error: 'Product not found' });
    } else {
      res.json(product);
    }
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

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

  try {
    const product = await Product.findByIdAndUpdate(id, req.body, { new: true });
    if (!product) {
      res.status(404).json({ error: 'Product not found' });
    } else {
      res.json(product);
    }
  } catch (error) {
    res.status(400).json({ error: error.message });
  }
});

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

  try {
    const product = await Product.findByIdAndDelete(id);
    if (!product) {
      res.status(404).json({ error: 'Product not found' });
    } else {
      res.json({ message: 'Product deleted successfully' });
    }
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

module.exports = router;

This code defines API routes for fetching all products, adding a new product, fetching a product by ID, updating a product by ID, and deleting a product by ID. Now, let’s connect these routes to the Express.js server.

Update the "server.js" file in the server folder with the following code:

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
const productRoutes = require('./routes/productRoutes');

const app = express();
const PORT = 5000;

app.use(cors());
app.use(bodyParser.json());
app.use('/products', productRoutes);

mongoose.connect('mongodb://localhost/computer-hardware-store', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

This code adds the product routes to the Express.js server. Now, when you start the server by running:

node server.js

You will have an API for managing computer hardware products. Next, let’s integrate the React front-end with the server-side.

Open the "App.js" file in the src folder of the React project and update it with the following code:

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

const App = () => {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    fetch('http://localhost:5000/products')
      .then((response) => response.json())
      .then((data) => setProducts(data))
      .catch((error) => console.error('Error:', error));
  }, []);

  return (
    <div>
      <h1>Welcome to Computer Hardware Store</h1>
      <ul>
        {products.map((product) => (
          <li key={product._id}>
            <h2>{product.name}</h2>
            <p>{product.description}</p>
            <p>${product.price}</p>
            <img src={product.image} alt={product.name} />
          </li>
        ))}
      </ul>
    </div>
  );
};

export default App;

This code fetches products from the API using the useEffect hook and displays them on the web page. Now, start the React development server by running:

npm start

You should see a list of computer hardware products displayed on the web page.

This tutorial demonstrated how to build an E-commerce website for computer hardware using the MERN stack. You learned how to create a server with Express.js, set up a MongoDB database, define models for products, create API routes for CRUD operations, and integrate the front-end with the back-end. You can further enhance this project by adding features like user authentication, product filtering, and shopping cart functionality. Happy coding!

0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x