0% found this document useful (0 votes)
2 views

Database Connectivity

This document provides a step-by-step guide to set up a full-stack application using Express.js for the backend and React for the frontend. It includes instructions for installing dependencies, creating server and client files, configuring MongoDB connections, and implementing data fetching with Axios. The final steps involve running both the Express server and the React application to create a functional app that allows users to manage items.

Uploaded by

kra26973
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Database Connectivity

This document provides a step-by-step guide to set up a full-stack application using Express.js for the backend and React for the frontend. It includes instructions for installing dependencies, creating server and client files, configuring MongoDB connections, and implementing data fetching with Axios. The final steps involve running both the Express server and the React application to create a functional app that allows users to manage items.

Uploaded by

kra26973
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Step 1: Set Up Express.

js Server

1. Install Dependencies:
In your project directory, create a new folder for your server (e.g.,
server). Inside this folder, initialize a new Node.js project and install
necessary dependencies:
1. bash
குறியீட்டை நகலெடுக்கவும்
mkdir server
cd server
npm init -y
npm install express mongoose cors

2. Create Server Files: Create a file named server.js inside the server folder.
3. Configure Express and MongoDB: In server.js, set up your Express server to
connect to MongoDB:

javascript
குறியீட்டை நகலெடுக்கவும்
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');

const app = express();


const port = 3001;

// Middleware
app.use(cors());
app.use(express.json());

// MongoDB connection
mongoose.connect('mongodb://localhost:27017/mydatabase', {
useNewUrlParser: true,
useUnifiedTopology: true,
});

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log('Connected to MongoDB');
});

// Define a simple schema and model


const itemSchema = new mongoose.Schema({
name: String,
});

const Item = mongoose.model('Item', itemSchema);

// Routes
app.get('/api/items', async (req, res) => {
try {
const items = await Item.find();
res.json(items);
} catch (err) {
res.status(500).json({ message: err.message });
}
});

app.post('/api/items', async (req, res) => {


const item = new Item({
name: req.body.name,
});
try {
const newItem = await item.save();
res.status(201).json(newItem);
} catch (err) {
res.status(400).json({ message: err.message });
}
});

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

Step 2: Set Up React Frontend

1. Create React App: In your project directory, create a new React application using
Create React App:

bash
குறியீட்டை நகலெடுக்கவும்
npx create-react-app client
cd client

2. Install Axios: Install Axios for making HTTP requests:

bash
குறியீட்டை நகலெடுக்கவும்
npm install axios

3. Fetch Data in React: Inside your client/src folder, create a component file named
Items.js and set up the fetch logic:

javascript
குறியீட்டை நகலெடுக்கவும்
// client/src/Items.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';

function Items() {
const [items, setItems] = useState([]);
const [name, setName] = useState('');

useEffect(() => {
axios.get('http://localhost:3001/api/items')
.then(response => {
setItems(response.data);
})
.catch(error => {
console.error('There was an error fetching the data!', error);
});
}, []);

const handleSubmit = (e) => {


e.preventDefault();
axios.post('http://localhost:3001/api/items', { name })
.then(response => {
setItems([...items, response.data]);
setName('');
})
.catch(error => {
console.error('There was an error creating the item!', error);
});
};

return (
<div>
<h1>Items</h1>
<ul>
{items.map(item => (
<li key={item._id}>{item.name}</li>
))}
</ul>
<form onSubmit={handleSubmit}>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<button type="submit">Add Item</button>
</form>
</div>
);
}

export default Items;

4. Render Component in App: In your client/src/App.js, render the Items


component:

javascript
குறியீட்டை நகலெடுக்கவும்
// client/src/App.js
import React from 'react';
import './App.css';
import Items from './Items';

function App() {
return (
<div className="App">
<header className="App-header">
<Items />
</header>
</div>
);
}

export default App;

Step 3: Run the Applications

1. Start the Express Server: In the server directory, start the Express server:

bash
குறியீட்டை நகலெடுக்கவும்
node server.js

2. Start the React Application: In the client directory, start the React application:

bash
குறியீட்டை நகலெடுக்கவும்
npm start

Explanation:

1. Express.js Server:
o server.js: This file sets up an Express server, connects to a MongoDB database,
defines a Mongoose schema/model, and sets up routes for getting and posting
items.
o Middleware: cors is used to allow cross-origin requests, and express.json() is
used to parse JSON bodies.
o MongoDB Connection: Mongoose is used to connect to MongoDB and define a
schema and model.
2. React Frontend:
o Items.js: This component fetches items from the server and allows users to add
new items.
o Axios: Used for making HTTP requests to the Express server.

By following these steps, you can set up a simple full-stack application with a React frontend
and an Express/MongoDB backend.

You might also like