Building a complete web application may seem like a monumental task, but with the MERN stack (MongoDB, Express, React, and Node.js), this process is greatly simplified. This article will guide you through the necessary steps to create a valid and functional application, providing a brief description of each technology and an example of practical implementation.
The MERN stack is a set of technologies used to develop full web applications, both on the client-side and the server-side. This stack includes:
Before you begin, make sure you have the following installed:
You can start a new project in a directory of your choice:
mkdir mern-app cd mern-app npm init -y
This command creates a package.json file that manages your project dependencies.
Install Express and other necessary dependencies:
npm install express mongoose cors dotenv
Now, create a new file in your project named server.js and add the following code:
const express = require('express'); const mongoose = require('mongoose'); const cors = require('cors'); require('dotenv').config(); const app = express(); const PORT = process.env.PORT || 5000; // Middleware app.use(cors()); app.use(express.json()); // Connect to MongoDB mongoose.connect(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('MongoDB connected')) .catch(err => console.log(err)); // Start the server app.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}`); });
Create a .env file and add your MongoDB connection URI:
MONGODB_URI=your_mongodb_uri_here
Models in Mongoose are schemas that define the structure of your data. Create a folder called models and a file called Item.js:
const mongoose = require('mongoose'); const ItemSchema = new mongoose.Schema({ name: { type: String, required: true, }, price: { type: Number, required: true, }, }); module.exports = mongoose.model('Item', ItemSchema);
To handle HTTP requests, you need to create the routes for your application. Create a folder called routes and a file called item.js:
const express = require('express'); const router = express.Router(); const Item = require('../models/Item'); // Get all items router.get('/', async (req, res) => { try { const items = await Item.find(); res.json(items); } catch (err) { res.status(500).json({ message: err.message }); } }); // Create a new item router.post('/', async (req, res) => { const item = new Item({ name: req.body.name, price: req.body.price, }); try { const savedItem = await item.save(); res.status(201).json(savedItem); } catch (err) { res.status(400).json({ message: err.message }); } }); module.exports = router;
Then, import the routes in server.js:
const itemRoutes = require('./routes/item'); app.use('/api/items', itemRoutes);
Use Create React App to initialize a new React application:
npx create-react-app client cd client npm start
In the client folder, install axios:
npm install axios
Create a file named ItemList.js in the src folder:
import React, { useEffect, useState } from 'react'; import axios from 'axios'; const ItemList = () => { const [items, setItems] = useState([]); useEffect(() => { const fetchItems = async () => { const res = await axios.get('http://localhost:5000/api/items'); setItems(res.data); }; fetchItems(); }, []); return ( <div> <h1>Item List</h1> <ul> {items.map(item => ( <li key={item._id}>{item.name} - ${item.price}</li> ))} </ul> </div> ); }; export default ItemList;
Then, update App.js to use ItemList:
import React from 'react'; import ItemList from './ItemList'; const App = () => { return ( <div> <ItemList /> </div> ); }; export default App;
Start the server and the React application separately:
Visit http://localhost:3000 in your browser, and you should see the list of items.
You can deploy your application using platforms like Heroku or Vercel. Set up your MongoDB Atlas database and all necessary settings to ensure that your application works correctly in production.
The MERN stack is a powerful tool for building complete and scalable web applications. In this article, you learned how to set up a basic application using MongoDB, Express, React, and Node.js. With this foundation, you can explore more functionalities and expand your application with new features. Take advantage of all the flexibility and power that this stack offers to develop innovative projects. Good luck!
Page loaded in 36.79 ms