-->npm install -g create-react-app
-->npx create-react-app your-app-name
-->cd app-name
-->npm start
-------------------------------------->Pr 1 - using props class
component<------------------------------
Q1)Using properties in Class Component
-------->Classprops.js---------------
import React from "react";
import { Component } from "react";
class Parent extends Component{
render()
{
return(
<div>
<h1>This is Parent Class {this.props.address}</h1>
<Child p_name ="Parent Name" p_age = "50" />
</div>
);
}
}
class Child extends Component{
render()
{
return(
<div>
<h2>This is Child component {this.props.p_name}
{this.props.p_age}
</h2>
</div>
);
}
}
export {Parent,Child};
---------->App.js--------------
import {Parent,Child} from "./Classprops";
function App() {
return (
<div className="App">
<Parent/>
<Child p_name="with just the child no parent"/>
</div>
);
}
export default App;
Q2 Using properties in Functional Components
-------->functional_props.js-------
import React from 'react';
export const Car = (props) => {
return(
<h2>I am a {props.name} !!!</h2>
)
}
export const Product = () =>
{
return(
<div>
<h1>Product details</h1>
<Car name="BMW"/>
</div>
)
}
---------->App.js------------
import {Car,Product} from "./functional_props";
function App() {
return (
<div className="App">
<Car/>
<Product/>
</div>
);
}
export default App;
------------------------------------>Pr 2 - using state in class
components<-------------------------------------
Q.1 Updating message using state
--------->stateclass.js------------------
import React from "react";
import { Component } from "react";
class Message extends Component{
constructor()
{
super()
this.state = {
message: "Welcome Visitors"
}
}
render()
{
return(
<div>
<h1> {this.state.message}</h1>
<button onClick={()=> this.changeMessage()
}>Click here</button>
</div>
)
}
changeMessage()
{
this.setState(
{
message:"Thank You for visiting!"
}
)
}
}
export default Message
---------->App.js-------------------
import Message from "./stateclass";
function App() {
return (
<div className="App">
<Message/>
</div>
);
}
export default App;
Q2 Create a counter in Reactjs
------------->counter.js-------------------
import React, { Component } from "react";
class Counter extends Component {
constructor() {
super();
this.state = {
count: 0
};
}
increment() {
this.setState((prevState) => ({
count: prevState.count + 1
}), () => {
console.log(this.state.count);
});
}
incrementFour() {
this.increment();
this.increment();
this.increment();
this.increment();
}
render() {
return (
<div>
{this.state.count} <br></br>
<button onClick={() => this.incrementFour()}>Increment</button>
</div>
);
}
}
export default Counter;
---------->App.js-------------------
import Counter from "./counter";
function App() {
return (
<div className="App">
<Counter/>
</div>
);
}
export default App;
---------------------------------------------->Pr 3- using state in fucntional
components<---------------------------------------------
Q.1 Create Counter using useState hook
--------->counter1.js---------------
import React, { useState } from 'react';
const Count1 = () => {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default Count1
---------->App.js----------------
import Count1 from "./counter1";
function App() {
return (
<div className="App">
<Count1/>
</div>
);
}
export default App;
Q2 Increment the age using useReducer hook
--------->functional_age.js-------------------
import { useReducer } from 'react';
function reducer(state, action) {
if (action.type === 'incremented_age') {
return {
age: state.age + 1
};
}
throw Error('Unknown action.');
}
export default function Counter1() {
const [state, dispatch] = useReducer(reducer, { age: 42 });
return (
<>
<button onClick={() => {
dispatch({ type: 'incremented_age' })
}}>
Increment age
</button>
<p>Hello! You are {state.age}.</p>
</>
);
}
---------->App.js----------------
import Counter1 from "./functional_age";
function App() {
return (
<div className="App">
<Counter1/>
</div>
);
}
export default App;
Q.3 Perform incrementation & decrementation using useReducer hook
---------->incre_decr.js---------------
import { useReducer } from 'react';
const initialState = {count: 0};
function reducer(state, action) {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new Error();
}
}
function Incredecre() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
Count: {state.count} <br></br>
<button onClick={() => dispatch({type: 'increment'})}>Increment by
1</button><br></br>
<button onClick={() => dispatch({type: 'decrement'})}>Decrement by 1</button>
</div>
);
}
export default Incredecre
----------->App.js---------------
import Incredecre from "./incre_decr";
function App() {
return (
<div className="App">
<Incredecre/>
</div>
);
}
export default App;
Q.4 Perform increment decrement and reset operation using useReducer hook
---------->incrdecr.js-----------
import { useReducer } from 'react';
const initialState = 0;
const reducer = (state, action) => {
switch (action) {
case "add":
return state + 1;
case "subtract":
return state - 1;
case "reset":
return 0;
default:
throw new Error("Error");
}
};
const Arithmetic = () => {
// Initialising useReducer hook
const [count, dispatch] = useReducer(reducer, initialState);
return (
<div>
<h2>{count}</h2>
<button onClick={() => dispatch("add")}>
Increment
</button>
<button onClick={() => dispatch("subtract")}>
decrement
</button>
<button onClick={() => dispatch("reset")}>
reset
</button>
</div>
);
};
export default Arithmetic;
----------App.js------------------
import Arithmetic from "./incrdecr";
function App() {
return (
<div className="App">
<Arithmetic/>
</div>
);
}
export default App;
-------------------------->Pr 4- Component Lifecycle<---------------------------
----->mount.js----------
import React from 'react'
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 3000)
}
render() {
return (
<h1>Ths is Mount: My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}
export default Header
---------->update.js---------------
import React from "react";
class Update extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
shouldComponentUpdate() {
return false;
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
}
render() {
return (
<div>
<h1>Update: My Favorite Color is {this.state.favoritecolor}</h1>
<button type="button" onClick={this.changeColor}>Change color</button>
</div>
);
}
}
class Getsnapshot extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
}
getSnapshotBeforeUpdate(prevProps, prevState) {
document.getElementById("div1").innerHTML =
"Before the update, the favorite was " + prevState.favoritecolor;
return null;
}
componentDidUpdate() {
document.getElementById("div2").innerHTML =
"The updated favorite is " + this.state.favoritecolor;
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<div id="div1"></div>
<div id="div2"></div>
</div>
);
}
}
export {Getsnapshot,Update};
----------------->unmount.js----------------
import { render } from "@testing-library/react"; import React from "react";
class Unmount extends React.Component {
constructor() {
super(); this.state = {
delete: false,
};
}
render() {
return (
<div>
<h1>User List</h1>
<button onClick={() => this.setState({ delete: !this.state.delete })}>
Delete Users</button>
{this.state.delete ? null : <User />}
</div>
);
}
}
class User extends React.Component {
componentWillUnmount() {
alert('Delete user successfully!');
}
render() {
return (
<div>
<h3>UserName: Rahul</h3>
<h3>Email: Rahul@gmail.com</h3>
</div>
)
}
}
export default Unmount;
------------>App.js-------------
import Header from './mount';
import {Update,Getsnapshot} from './update';
import Unmount from './unmount';
function App() {
return (
<div className="App">
<Header/>
<Update/>
<Getsnapshot/>
<Unmount/>
</div>
);
}
export default App;
----------------------->Pr 5 Event Handling-----------------------
Define a form submission event handler is using an arrow function that prevents the
default form submission behavior using **event.preventDefault()**. Update the input
value using the **handleInputChange** function, which is called on every input
change event.
------->eventHandling.js------
import React, {useState} from 'react';
function Pr () {
const [inputValue,setInputValue] = useState('');
const handleSubmit = (event)=>{
event.preventDefault();
console.log('Submitted Value:', inputValue);
};
const handleInputChange = (event) => {
setInputValue(event.target.value);
};
return(
<form onSubmit={handleSubmit}>
<input type='text' value={inputValue} onChange={handleInputChange}/>
<button type="submit">Submit</button>
<h2>submitted value {inputValue}</h2>
</form>
);
}
export default Pr;
Define a keydown event handler is using an arrow function that checks if the Enter
key is pressed and logs the input value to the console. Update the the input value
using the **handleInputChange**function, which is called on every input change
event.
--------->eventHandling2.js------
import React,{useState} from 'react';
function KeyDown() {
const [inputValue, setInputValue] = useState('');
const handleKeyDown = (event) => {
if(event.key==="Enter"){
console.log('Submitted value:',inputValue);
}
};
const handleInputChange = (event) => {
setInputValue(event.target.value);
};
return(
<div>
<input type='text' value={inputValue} onKeyDown={handleKeyDown}
onChange={handleInputChange}/>
<p>{inputValue}</p>
</div>
)
}
export default KeyDown;
Take an input field to add an element into array using states.
------->eventHandling3.js------
import React from "react";
import { useState } from "react";
function MultiValuesArray(){
const friendsArray = ['Earth','Bright','Jeff',"Mew"]
const [friends,setFriends] = useState(friendsArray);
const handleFucntion = () => {
const newFriend = document.getElementById("friend").value
setFriends([...friends,newFriend])
}
return(
<div>
<h1>List</h1>
<ul>{friends.map((f,index) => <li key={index}> {f} </li>)}
</ul>
<input type="text" id="friend" placeholder="Enter friend name" />
<button onClick={handleFucntion}> Add Values</button>
</div>
)
}
export default MultiValuesArray;
Take a button to add users, remove user and add user after a specific element
-------------->eventHandling4.js--------
import React, { useState } from "react";
function AddRemoveArr(){
const [users,setUsers] = useState([
{id:1,username:"User 1"},
{id:4,username:"User 2"},
{id:3,username:"User 3"},
]);
const addUser = () => {
const newUser = {
id:`${users.length + 1}`,
username:`User ${users.length + 1}`
};
const newUsers = [...users,newUser];
setUsers(newUsers)
};
const removeUser = (index) => () =>{
const newUsers = [...users];
console.log(newUsers);
newUsers.splice(index,1);
setUsers(newUsers);
}
const addAfter = (index) => () => {
const newUser = {
id:`${users.length + 1}`,
username:`User ${users.length + 1}`
}
const newUsers =[...users];
newUsers.splice(index + 1,0,newUser)
console.log(newUser)
setUsers(newUsers);
};
return(
<>
<button onClick={addUser}>Add User</button>
{users.map((user,index)=>(
<div className="user" key={user.id}>
{user.username}
<button onClick={removeUser(index)}>Remove User</button>
<button onClick={addAfter(index)}>Add immediate next User</button>
</div>
))}
</>)
}
export default AddRemoveArr;
-------->App.js-----------
import './App.css'
import Pr5i from './eventHandling'
import KeyDown from './eventHandling2'
import MultiValuesArray from './eventHandling3'
import AddRemoveArr from './eventHandling4'
function App() {
return (
<>
<Pr5i/>
<KeyDown/>
<MultiValuesArray/>
<AddRemoveArr/>
</>
)
}
export default App
------------------------>Pr 6 useEffect and useRef--------------------------
Countdown timer with useEffect
-------->TimerUseEffect.js----
import React, {useState,useEffect} from 'react'
function Pr(){
const [timeRemaining,setTimeReamining] = useState(10);
useEffect(()=>{
if(timeRemaining <=0){
return;
}
const timerId = setInterval(()=>{
setTimeReamining((prevTime) => prevTime - 1);
console.log('remaining time:',timeRemaining)
},1000);
return() =>{
console.log('Clearing up the time',timeRemaining)
clearInterval(timerId);
};
},[timeRemaining]);
return(
<div>
<p>Time Remaining: {timeRemaining}</p>
</div>
)
}
export default Pr;
Window Resize Listener using useEffect
------->WindowResize.js----
import React,{useState,useEffect} from 'react'
function WindowResizeComp(){
const [windowSize,setWindowSize] =
useState({width:window.innerWidth,height:window.innerHeight});
useEffect(()=>{
const handleResize = () =>{
setWindowSize({width: window.innerWidth, height: window.innerHeight});
};
window.addEventListener('resize',handleResize);
return()=>{
window.removeEventListener('resize',handleResize);
};
},[]);
return(
<div>
<p>Window size: {windowSize.width} x {windowSize.height}</p>
</div>
)
}
export default WindowResizeComp;
Form Input Validation with useEffect
----->InputValidation.js--------
import React, { useEffect, useState } from "react";
const FormInputValidationComponent = () =>{
const [inputValue,setInputValue] = useState('');
const [isValid,setIsValid] = useState(true);
useEffect(()=>{
console.log('Input value changed:',inputValue);
const isValidInput = inputValue.length > 5;
setIsValid(isValidInput);
},[inputValue]);
const handleInputChange = (event) => {
setInputValue(event.target.value)
}
const handleSubmit = (event) =>{
event.preventDefault();
if(isValid){
console.log('From submitted with valid input:', inputValue);
}
else{
console.log('Form submission blocked due to invalid
input:',inputValue);
}
};
return(
<div>
<form onSubmit={handleSubmit}>
<label>Enter Value</label>
<input
type="text"
value={inputValue}
onChange={handleInputChange}
style={{borderColor: isValid?'green':'red'}}
/>
<button type="submit">Submit</button>
</form>
{!isValid && <p style={{color:'red'}}>Input must have more than 5
characters</p>}
</div>
)
}
export default FormInputValidationComponent;
Data Fetching using useEffect
--------->DataFetching.js---------
import React, { useEffect, useState } from "react";
function DataFetchingComponent(){
const [posts,setPosts] = useState([]);
useEffect(()=>{
const fetchData = async () =>{
const response = await
fetch('https://jsonplaceholder.typicode.com/posts');
const data = await response.json();
setPosts(data);
};
fetchData()
},[]);
return(
<div>
<h1>Data Fetched</h1>
{posts.map((post) =>
<div>
{post.id}<br/>
Title:<h3>{post.title}</h3>
Body:<p>{post.body}</p>
</div>
)
}
</div>
)
}
export default DataFetchingComponent;
------->App.jsx-----
import './App.css'
import DataFetchingComponent from './DataFetching'
import FormInputValidationComponent from './InputValidation'
import Pr6i from './TimerUseEffect'
import WindowResizeComp from './WindowResize'
function App() {
return (
<>
<Pr6i/>
<WindowResizeComp/>
<FormInputValidationComponent/>
<DataFetchingComponent/>
</>
)
}
export default App
------------------------------>Pr 7 useRef<------------------------
Develop a React application that includes a form with input fields for username and
email address. Implement functionality to automatically focus on the username input
field when the page loads.
------->FocusInput.js-------
import React, { useEffect, useRef } from 'react';
export default function FocusInput() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current.focus();
}, []);
const focusInput = () => {
inputRef.current.focus();
};
return (
<div>
<h1>Focus Input Field</h1>
Username: <input type="text" ref={inputRef} />
<button onClick={focusInput}>Focus Input</button>
Email: <input type="text" />
</div>
);
}
Develop a React component called FormWithRef that implements a form with input
fields for username and email. Use the useRef hook to persist mutable values for
these input fields and to store the submitted data. The form should log the
submitted data to the console when the user submits the form.
------->FormWithRef.js-----
import React, { useRef } from 'react';
function FormWithRef() {
const usernameRef = useRef('');
const emailRef = useRef('');
const submittedDataRef = useRef(null);
const handleSubmit = (event) => {
event.preventDefault();
const username = usernameRef.current.value;
const email = emailRef.current.value;
submittedDataRef.current = { username, email };
usernameRef.current.value = '';
emailRef.current.value = '';
console.log('Submitted Data:', submittedDataRef.current);
};
return (
<div>
<h2>Form with Ref</h2>
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="username">Username:</label>
<input
type="text"
id="username"
ref={usernameRef}
/>
</div>
<div>
<label htmlFor="email">Email:</label>
<input
type="email"
id="email"
ref={emailRef}
/>
</div>
<button type="submit">Submit</button>
</form>
</div>
);
}
export default FormWithRef;
Develop a React application that demonstrates parent-child interaction using the
useImperativeHandle hook. Create a parent component and a child component. The
child component should have a method that, when called by the parent component,
displays a message.
------->ImperativeHandle.js------
import React, { useRef, useImperativeHandle, forwardRef } from 'react';
const ChildComponent = forwardRef((props, ref) => {
const greetParent = () => {
console.log('Hello from Child Component!');
};
useImperativeHandle(ref, () => ({
greetParent: greetParent
}));
return (
<div>
<h3>Child Component</h3>
</div>
);
});
function Parent() {
const childRef = useRef(null);
const handleButtonClick = () => {
childRef.current.greetParent();
};
return (
<div>
<h2>Parent Component</h2>
<button onClick={handleButtonClick}>Greet Child</button>
<ChildComponent ref={childRef} />
</div>
);
}
export default Parent;
------>App.js----
import './App.css'
import FocusInput from './FocusInput'
import FormWithRef from './FormWithRef'
import Parent from './ImperativeHandle'
function App() {
return (
<>
<FocusInput/>
<FormWithRef/>
<Parent/>
</>
)
}
export default App
------------------------------------------------->Pr 8
Router<----------------------------------
a) Create three main pages: Home, About, and Contact. Each page should have a
unique URL path. Implement navigation links to switch between the pages.
b) Implement nested routing. Let the contact component have two nested links Add
and Display contact.
-->React Router Installation
npm install react-router-dom@6
---------->Components.js--------------
import React from "react";
import { Link } from "react-router-dom";
export function Home() {
return (
<div>
<h1>This is the home page</h1>
<Link to="About">Click to view about page</Link>
<Link to="Contact">Click to view contact page</Link>
</div>
);
}
export function About() {
return (
<div>
<h1>This is the About page</h1>
<Link to="/">Click to go back to home page</Link>
</div>
);
}
export function Add() {
return (
<div>
<h2>Add contact</h2>
</div>
);
}
export function Display() {
return (
<div>
<h2>Display contact</h2>
</div>
);
}
export function Contact() {
return (
<div>
<h1>This is the Contact page</h1>
<Link to="/">Click to go back to home page</Link>
<nav>
<ul>
<li>
<Link to='add'>Add Contact</Link>
</li>
<li>
<Link to="display">Display Contacts</Link>
</li>
</ul>
</nav>
</div>
);
}
---------->App.js------------
import './App.css'
import { BrowserRouter as Router, Route, Routes } from "react-router-dom"
import { About, Add, Contact, Display, Home } from './Components'
function App() {
return (
<div className='App'>
<Router>
<Routes>
<Route path='/' element={<Home/>}/>
<Route path='About' element={<About/>}/>
<Route path='Contact' element={<Contact/>}>
<Route path="add" element={<Add/>}/>
<Route path="display" element={<Display/>}/>
</Route>
</Routes>
</Router>
</div>
)
}
export default App
--------------------------------->Pr 9 node file
operations<---------------------------
->Create Folder Nodejs->open in vs code
-->don't create any project folder
-->for run the code ->node filename.js
-->npm init --> keep press enter enter ->yes --> in terminal
-->npm install express -->in terminal
-------->readfile.js---- [ create txt file as text.txt ]
const fs = require("fs");
// Synchronously reading file
const contentSync = fs.readFileSync('./text.txt', "utf-8");
console.log("Content read synchronously:", contentSync);
// Asynchronously reading file
fs.readFile("./text.txt", "utf-8", (error, data) => {
if (error) {
throw new Error('Error reading file!');
}
console.log("Content read asynchronously:", data);
});
// Reading file within an async function
async function readFileAsync() {
try {
const data = await fs.promises.readFile("text.txt", "utf-8");
console.log("Content read within async function:", data);
} catch (error) {
console.log("Error reading file within async function:", error);
} }
readFileAsync();
------>writefile.js---------
const fs = require("fs/promises");
const writeFunct = async () => {
try {
try {
await fs.access("example.txt");
} catch (error) {
await fs.writeFile("example.txt", "Initial content", "utf-8");
}
const d = await fs.readFile("example.txt", "utf-8");
console.log(d);
await fs.writeFile("example.txt", "Writing in a file", "utf-8");
await fs.appendFile("example.txt", "\n data append via node.js", "utf-8");
await fs.rename("example.txt", "NewWrite.txt");
const data = await fs.readFile("NewWrite.txt", "utf-8");
console.log(data);
await fs.unlink("NewWrite.txt");
console.log("File deleted successfully");
} catch (err) {
console.error("Error:", err);
}
};
writeFunct();
---------->input.js-------
const fs = require('fs');
const readline = require('readline');
const EventEmitter = require('events');
const eventEmitter = new EventEmitter();
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function handleInput(input) {
eventEmitter.emit('textReady', input);
}
eventEmitter.on('textReady', (text) => {
console.log(`Custom event fired: Text is ready - ${text}`);
fs.writeFile('text.txt', text, (err) => {
if (err) throw err;
console.log('Text has been saved to text.txt');
rl.close();
});
});
rl.question('Enter some text: ', (text) => {
handleInput(text);
});
--------->server.js--------------
[ For Run
-->node server.js ->in vs code ]
[ in chrome ]
-->http://127.0.0.2:3000/
-->http://127.0.0.2:3000/about
-->http://127.0.0.2:3000/home
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
if (req.url === '/hello') {
res.end('Hello World!\n');
} else if (req.url === '/about') {
res.end('This is the about page.\n');
} else {
res.end('Node.js server!\n');
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
---------------------------->Pr 10 - Creating servers using express and handling
http methods <--------------------------
->Create Folder Nodejs->open in vs code
-->don't create any project folder
-->install thunderclient extension
Initial Commands to run on the console:
npm init -->keep press enter - enter ->yes
npm install express
To run a file, node filename.js
----------------------------------------
Q1)"Create a Node.js program using Express that serves a list of users from a JSON
file.
The program should define an API endpoint to retrieve the details of users in JSON
format.
a. Display details of all users
b. Display details based on its parameters such as id"
create users.json ---
[
{
"id": 1,
"name": "jayshreeram",
"age": 19
},
{
"id": 2,
"name": "gada",
"age": 19
},
{},
{
"id": 3,
"name": "pada",
"age": 45
},
{ "id": 4,
"name": "baba",
"age": 50
}
]
--------------index.js ---------------
const express = require('express');
const fs = require('fs');
const app = express();
app.use(express.json());
const userData = JSON.parse(fs.readFileSync('users.json'));
app.get('/users', (req, res) => {
res.json(userData);
});
app.get('/users/:id', (req, res) => {
const userId = parseInt(req.params.id);
const user = userData.find(user => user.id === userId);
if (!user) {
return res.status(404).json({ message: "User not found" });
}
res.json(user);
});
app.listen(3000, () => {
console.log("running on 3000");
});
op path
a)http://localhost:3000/users/
b)http://localhost:3000/users/1
-----------------------------------------------------------------------------------
--
Q2)Update the name of the user whose id is 2. (Using patch method)
const express = require('express');
const app = express();
const fs = require('fs');
app.use(express.json());
let userData = JSON.parse(fs.readFileSync('users.json'));
app.patch('/users/:id', (req, res) => {
const userId = parseInt(req.params.id);
const newName = req.body.name;
const userIndex = userData.findIndex(user => user.id === userId);
if (userIndex === -1) {
return res.status(404).json({ message: "User not found" });
}
userData[userIndex].name = newName;
fs.writeFileSync('users.json', JSON.stringify(userData, null, 2));
res.json(userData[userIndex]);
});
app.listen(8080, () => {
console.log("running on port 3000");
});
op pacth http://localhost:3000/users/2
boby tag {"name":"ssasa"}
-----------------------------------------------------------------------------------
-------------
Q3)
a Add a new user in JSON file and send a response.
b. Delete a user whose id is 5. Send a response after performing delete operation."
const express = require('express');
const app = express();
const fs = require('fs');
app.use(express.json());
let userData = JSON.parse(fs.readFileSync('users.json'));
app.post('/addusers', (req, res) => {
const newUser = req.body;
userData.push(newUser);
fs.writeFileSync('users.json', JSON.stringify(userData, null, 2));
res.json(newUser);
});
app.delete('/delusers/:id', (req, res) => {
const userId = parseInt(req.params.id);
const userIndex = userData.findIndex(user => user.id === userId);
if (userIndex === -1) {
return res.status(404).json({ message: "User not found" });
}
userData.splice(userIndex, 1);
fs.writeFileSync('users.json', JSON.stringify(userData, null, 2));
res.json({ message: "User deleted successfully" });
});
app.listen(3000, () => {
console.log(`running at 3000`);
});
op post http://localhost:3000/addusers
boby tAG{
"id": 4,
"name": "baba",
"age": 50
}
delete http://localhost:3000/delusers/4
---------------------------------------------------------------
npm install nodemon
npm install mongoose
Q4)"Connect nodejs with MongoDB.
a. Create Database
b. Create Collection"
// server.js
const express = require('express');
const mongoose = require('mongoose');
const app = express();
app.use(express.json());
const PORT = 3000;
// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase')
.then(() => {
console.log('Connected to MongoDB');
})
.catch((error) => {
console.error('Error connecting to MongoDB:', error);
});
// Define schema and model
const exampleSchema = new mongoose.Schema({
name: String,
age: Number
});
const ExampleModel = mongoose.model('Example', exampleSchema);
// Insert data into the collection
const exampleData = new ExampleModel({
name: 'John Doe',
age: 25
});
// http methods handling
// Get data
app.get('/data', (req, res) => {
ExampleModel.find()
.then(data => {
res.json(data);
})
.catch(err => {
res.status(500).send(err);
});
});
// Post new data
app.post('/data', (req, res) => {
console.log (req.body.name);
const newData = new ExampleModel(req.body);
newData.save()
.then(result => {
res.json(result);
})
.catch(err => {
res.status(500).send(err);
});
});
// Update data
app.put('/data/:id', (req, res) => {
ExampleModel.findByIdAndUpdate(req.params.id, req.body, { new: true })
.then(updatedData => {
res.json(updatedData);
})
.catch(err => {
res.status(500).send(err);
});
});
// Delete data
app.delete('/data/:id', (req, res) => {
ExampleModel.findByIdAndDelete(req.params.id)
.then(() => {
res.send('Data deleted successfully');
})
.catch(err => {
res.status(500).send(err);
});
});
exampleData.save()
.then(result => {
console.log('Data saved successfully:', result);
})
.catch(err => {
console.error('Error saving data:', err);
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});