Database Connectivity
Database Connectivity
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');
// 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');
});
// 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.listen(port, () => {
console.log(`Server running on port ${port}`);
});
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
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);
});
}, []);
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>
);
}
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>
);
}
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.