React Node.js MongoDB Database Connection Tutorial
React Node.js MongoDB Database Connection Tutorial is a simple guide to help you connect your React app with a Node.js backend and MongoDB database. This tutorial is perfect for beginners who want to learn how the frontend and backend work together with a database.
In this article, we will go through step-by-step how to set up the React project, create an API using Node.js, and connect it with MongoDB. Everything is explained in very easy language.
Step 1: Create React JS Project
To create a new React project, use the below command. This will start a Vite-powered React setup.
npm create vite@latest react-frontend --template
Then install Axios to make API calls.
npm install axios
Step 2: Update App.tsx File
Now open the src/App.tsx file and update it like below. It will call the API and show data in a table.
import axios from "axios";
import { useEffect, useState } from "react"
function App() {
const [posts, setPosts] = useState([]);
useEffect(() => {
axios.get("http://localhost:8000/api/posts").then((res) => {
setPosts(res.data);
})
})
return (
<>
<div className='p-4'>
<h1>Sample Data</h1>
<table className="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Body</th>
</tr>
</thead>
<tbody>
{posts.map((post) =>
<tr>
<td>{post._id}</td>
<td>{post.title}</td>
<td>{post.body}</td>
</tr>
)}
</tbody>
</table>
</div>
</>
)
}
export default App
Step 3: Create Node App
To create the Node.js backend, first create a folder and initialize the project.
mkdir node-beckend
npm init -y
npm install express mongoose cors
Step 4: Create posts API
Now create a file named server.js and add the following code.
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const Post = require("./models/Post");
const PORT = 8000;
const app = express();
app.use(cors());
app.use(express.json());
// MongoDB Database Connection
mongoose.connect("mongodb://127.0.0.1:27017/myapp")
.then(() => console.log("MongoDB connected"))
.catch((err) => console.error("MongoDB error", err));
// API
app.get("/api/posts", async (req, res) => {
const posts = await Post.find();
res.json(posts);
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
Step 5: Create Post model
Now create a file models/Post.js and add the schema.
const mongoose = require("mongoose");
const postSchema = new mongoose.Schema({
title: String,
body: String
}, {timestamps: true});
module.exports = mongoose.model('Post', postSchema);
Run Node JS & React JS App:
Run your node app like this:
node server.js
Now run the react js app:
npm run dev
Now, Go to your web browser, type the given URL and view the app output:
http://localhost:5173
Now you can use.