Assignments Of Day 29: MongoDB with React.js

Rashmi Mishra
0

Assignments Of  Day 29

MongoDB with React.js

Assignment 1: Set Up the Backend (Express.js with MongoDB)

Objective: Set up a basic Express.js server and connect it to MongoDB.

Steps:

1.   Create a new Node.js project: Initialize your project with npm init.

2.   Install dependencies: Install express, mongoose, cors, and dotenv:

npm install express mongoose cors dotenv

3.   Create a server file (server.js):

const express = require('express');

const mongoose = require('mongoose');

const cors = require('cors');

require('dotenv').config();

 

const app = express();

const PORT = process.env.PORT || 5000;

 

app.use(cors());

app.use(express.json());

 

// MongoDB connection

mongoose.connect(process.env.MONGO_URI, {

  useNewUrlParser: true,

  useUnifiedTopology: true,

}).then(() => console.log('MongoDB connected'))

  .catch(err => console.log(err));

 

app.listen(PORT, () => {

  console.log(`Server running on port ${PORT}`);

});

4.   Create .env file for MongoDB URI:

MONGO_URI=mongodb://localhost:27017/mydb


Assignment 2: Create a User Model for MongoDB

Objective: Define a User model with name, email, and password.

Steps:

1.   Create a model (models/User.js):

const mongoose = require('mongoose');

 

const userSchema = new mongoose.Schema({

  name: { type: String, required: true },

  email: { type: String, required: true, unique: true },

  password: { type: String, required: true }

});

 

const User = mongoose.model('User', userSchema);

module.exports = User;

2.   Explanation:

o    The schema defines name, email, and password as required fields for users.

o    unique: true ensures that the email is unique in the database.


Assignment 3: Create a Signup Route (POST)

Objective: Create a POST route for user signup.

Steps:

1.   Create a new route for signup (routes/auth.js):

const express = require('express');

const bcrypt = require('bcryptjs');

const User = require('../models/User');

 

const router = express.Router();

 

router.post('/signup', async (req, res) => {

  const { name, email, password } = req.body;

 

  try {

    const hashedPassword = await bcrypt.hash(password, 10);

    const newUser = new User({ name, email, password: hashedPassword });

    await newUser.save();

    res.status(201).json({ message: 'User created successfully' });

  } catch (error) {

    res.status(400).json({ message: error.message });

  }

});

 

module.exports = router;

2.   Explanation:

o    We hash the password using bcryptjs before saving the user in the database.

o    The server responds with a success message if the user is created.


Assignment 4: Create a Login Route (POST) with JWT

Objective: Implement a login route that issues a JWT token upon successful authentication.

Steps:

1.   Create a login route (routes/auth.js):

const jwt = require('jsonwebtoken');

 

router.post('/login', async (req, res) => {

  const { email, password } = req.body;

 

  try {

    const user = await User.findOne({ email });

    if (!user) {

      return res.status(400).json({ message: 'Invalid credentials' });

    }

 

    const isMatch = await bcrypt.compare(password, user.password);

    if (!isMatch) {

      return res.status(400).json({ message: 'Invalid credentials' });

    }

 

    const token = jwt.sign({ userId: user._id }, 'your_jwt_secret', { expiresIn: '1h' });

    res.json({ token });

  } catch (error) {

    res.status(400).json({ message: error.message });

  }

});

2.   Explanation:

o    After checking if the user exists and validating the password, we generate a JWT token using jsonwebtoken.

o    The token expires in 1 hour.


Assignment 5: Set Up React for Frontend

Objective: Set up a React project with React Router.

Steps:

1.   Create a React project using Vite:

npm create vite@latest my-app --template react

2.   Install React Router:

npm install react-router-dom

3.   Setup React Router in App.js:

import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';

import Login from './pages/Login';

import Signup from './pages/Signup';

 

function App() {

  return (

    <Router>

      <Routes>

        <Route path="/login" element={<Login />} />

        <Route path="/signup" element={<Signup />} />

      </Routes>

    </Router>

  );

}

 

export default App;


Assignment 6: Implement Signup Form in React

Objective: Create a React signup form that sends a POST request to the backend.

Steps:

1.   Create Signup.js in src/pages/Signup.js:

import React, { useState } from 'react';

import axios from 'axios';

 

const Signup = () => {

  const [name, setName] = useState('');

  const [email, setEmail] = useState('');

  const [password, setPassword] = useState('');

 

  const handleSubmit = async (e) => {

    e.preventDefault();

    try {

      await axios.post('http://localhost:5000/api/signup', { name, email, password });

      alert('Signup successful!');

    } catch (error) {

      console.error(error.message);

    }

  };

 

  return (

    <form onSubmit={handleSubmit}>

      <input type="text" placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} />

      <input type="email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} />

      <input type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} />

      <button type="submit">Sign Up</button>

    </form>

  );

};

 

export default Signup;


Assignment 7: Implement Login Form in React

Objective: Create a React login form that sends a POST request to the backend and stores the JWT.

Steps:

1.   Create Login.js in src/pages/Login.js:

import React, { useState } from 'react';

import axios from 'axios';

 

const Login = () => {

  const [email, setEmail] = useState('');

  const [password, setPassword] = useState('');

  const [token, setToken] = useState('');

 

  const handleLogin = async (e) => {

    e.preventDefault();

    try {

      const response = await axios.post('http://localhost:5000/api/login', { email, password });

      setToken(response.data.token);

      localStorage.setItem('token', response.data.token); // Store the token

      alert('Login successful!');

    } catch (error) {

      console.error(error.message);

    }

  };

 

  return (

    <form onSubmit={handleLogin}>

      <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email" />

      <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Password" />

      <button type="submit">Login</button>

    </form>

  );

};

 

export default Login;


Assignment 8: Create a Delete User Functionality

Objective: Implement the ability to delete users on both the backend and frontend.

Steps:

1.   Backend: Add Delete Route:

router.delete('/users/:id', async (req, res) => {

  try {

    const deletedUser = await User.findByIdAndDelete(req.params.id);

    if (!deletedUser) return res.status(404).json({ message: 'User not found' });

    res.status(200).json({ message: 'User deleted' });

  } catch (error) {

    res.status(500).json({ message: error.message });

  }

});

2.   Frontend: Add Delete Button:

const deleteUser = async (id) => {

  try {

    await axios.delete(`http://localhost:5000/api/users/${id}`);

    setUsers(users.filter(user => user._id !== id));

  } catch (error) {

    console.error('Error deleting user', error);

  }

};


Assignment 9: Display User List on Frontend

Objective: Fetch and display a list of users from the backend.

Steps:

1.   Create User List Component:

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

import axios from 'axios';

 

const UserList = () => {

  const [users, setUsers] = useState([]);

 

  useEffect(() => {

    const fetchUsers = async () => {

      const response = await axios.get('http://localhost:5000/api/users');

      setUsers(response.data);

    };

    fetchUsers();

  }, []);

 

  return (

    <ul>

      {users.map(user => (

        <li key={user._id}>{user.name} - {user.email}</li>

      ))}

    </ul>

  );

};

 

export default UserList;


Assignment 10: Implement User Authentication Middleware

Objective: Secure API routes using JWT authentication middleware.

Steps:

1.   Create Authentication Middleware:

const jwt = require('jsonwebtoken');

 

const authenticate = (req, res, next) => {

  const token = req.header('x-auth-token');

  if (!token) return res.status(401).json({ message: 'No token, authorization denied' });

 

  try {

    const decoded = jwt.verify(token, 'your_jwt_secret');

    req.user = decoded.userId;

    next();

  } catch (err) {

    res.status(400).json({ message: 'Invalid token' });

  }

};

 

module.exports = authenticate;

2.   Use Middleware on Protected Routes:

const authenticate = require('./middleware/authenticate');

router.get('/protected', authenticate, (req, res) => {

  res.json({ message: 'Protected route access granted' });

});



Post a Comment

0Comments

Post a Comment (0)

About Me