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

Lab File Format PDF

This document provides a high-level overview of building a simple web application using Node.js, Express, and React that implements user authentication and authorization in 3 main steps: 1) Setting up the backend server with Node.js/Express and frontend with React, 2) Implementing authentication functionality on the backend like user registration/login, password hashing, and JWT tokens, 3) Creating frontend components and pages for login, signup, and a protected dashboard page for authenticated users to access.

Uploaded by

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

Lab File Format PDF

This document provides a high-level overview of building a simple web application using Node.js, Express, and React that implements user authentication and authorization in 3 main steps: 1) Setting up the backend server with Node.js/Express and frontend with React, 2) Implementing authentication functionality on the backend like user registration/login, password hashing, and JWT tokens, 3) Creating frontend components and pages for login, signup, and a protected dashboard page for authenticated users to access.

Uploaded by

TECHNO YASH
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Programming File:

Course Name:
Course Code:

B.Sc. Computer Science


2nd Year, Semester- 4
Session 2021-24

Department of Computer Applications

Programmer Name: Faculty:


AMAR SINGH
Enrollment no.:
Asst. Professor
SCSE

School of Computing Science and Engineering

Galgotias University
Plot No. 2, Sector-17A, Yamuna Expressway, Greater Noida, Gautam Buddha Nagar, Uttar
Pradesh, India Contact no. 0120–4370000,
Index
S.NO CONTENTS SIGNATURE

Build a program to create CRUD operation using php with mysql


1 database

Building a simple CRUD (Create, Read, Update, Delete) web application


2 using Node.js and a SQL database.

Building a simple web application using Node.js, Express and React that
3 implements user authentication and authorization.

Building a web application using Node.js and React that consumes data
4 from a REST API.

Building a web application using Node.js, React, and a NoSQL database


5 that implements server-side rendering.
Building a web application using Node.js, React and Webpack for asset
6 management and optimization.

Building a web application using Node.js, React and Redux for state
7 management.

Building a web application using Node.js, React and Jest for unit testing.
8

Building a web application using Node.js and React that uses


9 websockets for real-time communication between the client and the
server.

Building a web application using Node.js, React, and a NoSQL database


10 that implements server-side rendering.

Building a web application using Node.js and React that consumes data
11 from a REST API.

Building a web application using Node.js, React and Webpack for asset
12 management and optimization.
Building a web application using Node.js and React that uses the latest
13 features of ECMAScript and Label.
LAB-1

write a program to create CRUD operation using php with mysql database
// Database connection parameters
$host = 'localhost';
$username = 'your_username';
$password = 'your_password';
$database = 'your_database';

// Connect to the database


$conn = mysqli_connect($host, $username, $password, $database);

// Check the connection


if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// CREATE operation
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Retrieve data from the form
$name = $_POST['name'];
$email = $_POST['email'];

// Insert data into the database


$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if (mysqli_query($conn, $sql)) {
echo "Record created successfully.";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}

// READ operation
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
// Display the data
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row['id'] . "<br>";
echo "Name: " . $row['name'] . "<br>";
echo "Email: " . $row['email'] . "<br><br>";
}
} else {
echo "No records found.";
}

// UPDATE operation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update'])) {
$id = $_POST['id'];
$newName = $_POST['newName'];
$newEmail = $_POST['newEmail'];

$sql = "UPDATE users SET name='$newName', email='$newEmail' WHERE id='$id'";


if (mysqli_query($conn, $sql)) {
echo "Record updated successfully.";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
}

// DELETE operation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete'])) {
$id = $_POST['id'];

$sql = "DELETE FROM users WHERE id='$id'";


if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully.";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
}

// Close the database connection


mysqli_close($conn);

?>

<!-- HTML form for creating and updating records -->


<form method="POST" action="">
<label for="name">Name:</label>
<input type="text" name="name" id="name" required><br>

<label for="email">Email:</label>
<input type="email" name="email" id="email" required><br>

<button type="submit">Create</button>
</form>

<!-- HTML form for updating and deleting records -->


<form method="POST" action="">
<label for="id">ID:</label>
<input type="text" name="id" id="id" required><br>

<label for="newName">New Name:</label>


<input type="text" name="newName" id="newName" required><br>

<label for="newEmail">New Email:</label>


<input type="email" name="newEmail" id="newEmail" required><br>
Lab-2

Building a simple CRUD (Create, Read, Update, Delete) web application using Node.js
and a SQL database.
Certainly! Here's an example of a simple CRUD web application using Node.js and a SQL database (MySQL):

1. Set up the project:


- Create a new directory for your project.
- Open a command prompt or terminal in that directory.
- Initialize a new Node.js project using `npm init` and follow the prompts.
- Install the necessary dependencies:
```
npm install express mysql body-parser ejs
```

2. Create the necessary files:


- Create an `index.js` file for the main application logic.
- Create a `views` folder and within it, create an `index.ejs` file for the homepage template.
- Create a `public` folder to store static files (e.g., CSS stylesheets).

3. Set up the database:


- Install MySQL on your machine if you haven't already.
- Create a new MySQL database.
- Create a table called `users` with columns for `id`, `name`, and `email`.

4. Configure the database connection:


- In the `index.js` file, require the necessary modules:
```javascript
const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const ejs = require('ejs');
```

- Set up the Express app and configure middleware:


```javascript
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
```

- Set up the MySQL connection:


```javascript
const db = mysql.createConnection({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'your_database'
});

db.connect((err) => {
if (err) throw err;
console.log('Connected to MySQL database');
});
```

5. Implement the CRUD routes:


- Create route for the homepage:
```javascript
app.get('/', (req, res) => {
db.query('SELECT * FROM users', (err, results) => {
if (err) throw err;
res.render('index', { users: results });
});
});
```

- Create routes for creating, updating, and deleting users:


```javascript
app.post('/create', (req, res) => {
const { name, email } = req.body;
const newUser = { name, email };
db.query('INSERT INTO users SET ?', newUser, (err, result) => {
if (err) throw err;
res.redirect('/');
});
});

app.post('/update/:id', (req, res) => {


const { name, email } = req.body;
const userId = req.params.id;
db.query(
'UPDATE users SET name = ?, email = ? WHERE id = ?',
[name, email, userId],
(err, result) => {
if (err) throw err;
res.redirect('/');
}
);
});

app.post('/delete/:id', (req, res) => {


const userId = req.params.id;
db.query('DELETE FROM users WHERE id = ?', userId, (err, result) => {
if (err) throw err;
res.redirect('/');
});
});
```

6. Create the views:


- In the `index.ejs` file, display the list of users and provide a form for creating, updating, and deleting users.

- Example `index.ejs` content:


```html
<!DOCTYPE html>
<html>
Lab-3

Building a simple web application using Node.js, Express and React that implements user
authentication and authorization

Sure! Here's a high-level overview of building a simple web application using Node.js, Express, and React that implements user
authentication and authorization:

1. Set up the project:


- Create a new directory for your project.
- Set up a backend server using Node.js and Express.
- Set up a frontend client using React.

2. Backend Server (Node.js and Express):


- Install the necessary dependencies:
```
npm install express bcrypt jsonwebtoken dotenv
```

- Create the necessary files:


- `index.js` - The main entry point for your backend server.
- `routes/auth.js` - Contains routes for user authentication (login, signup, logout).
- `routes/protected.js` - Contains routes that require authentication.
- `middlewares/authMiddleware.js` - Middleware to handle user authentication.

- Implement the following features in your backend server:


- User registration and storing user information in a database (e.g., MongoDB, PostgreSQL).
- User login and password validation using bcrypt for hashing and comparing passwords.
- Generating JSON Web Tokens (JWT) upon successful login.
- Protecting routes that require authentication using the authMiddleware.
- Implementing logout functionality.

3. Frontend Client (React):


- Set up the necessary packages and dependencies using Create React App or your preferred setup.
- Create the necessary components and pages:
- `LoginPage` - Allows users to enter their credentials to log in.
- `SignupPage` - Allows users to register a new account.
- `DashboardPage` - The main page for authenticated users, showing protected content.
- `Navbar` - A navigation component to switch between pages.

- Implement the following features in your frontend client:


- User interface for login and signup forms, using controlled components to handle form input.
- Utilize React Router to handle routing and page navigation.
- Communicate with the backend server using APIs (e.g., Axios) to handle user authentication (login, signup).
- Store JWT in the browser's local storage or cookies after successful login.
- Implement protected routes that redirect unauthenticated users to the login page.
- Display user-specific content on the dashboard page.

4. Authentication Flow:
- User Registration:
- Display a signup form where users can enter their desired credentials (e.g., username, email, password).
- On form submission, send a POST request to the backend server to create a new user account.
- Store the user's JWT token in the browser's local storage or cookies.
- User Login:
- Display a login form where users can enter their credentials (e.g., username, email, password).
- On form submission, send a POST request to the backend server to validate the user's credentials.
- If the credentials are valid, store the user's JWT token in the browser's local storage or cookies.

- Protected Routes:
- Define routes that require authentication on the backend server.
- On the frontend client, implement protected routes using React Router.
- Check for the presence of a valid JWT token in the browser's local storage or cookies before accessing protected routes.
- If the token is invalid or missing, redirect the user to the login page.

- Logout:
- Provide a logout button or link to allow users to log out.
- On logout, remove the JWT token from the browser's local storage or cookies.

5. Test and Deployment:


- Test your application thoroughly, including different scenarios for user authentication and authorization.
- Deploy your backend server and frontend client separately or together on a hosting platform of your choice (e.g., Heroku, AWS,
Netlify).
Lab-4

Building a web application using Node.js and React that consumes data from a REST API.
Certainly! Here's a high-level overview of building a web application using Node.js and React that consumes data from a REST API:

1. Set up the project:


- Create a new directory for your project.
- Set up a backend server using Node.js and Express to provide the REST API.
- Set up a frontend client using Create React App or your preferred setup.

2. Backend Server (Node.js and Express):


- Install the necessary dependencies:
```
npm install express cors
```

- Create the necessary files:


- `index.js` - The main entry point for your backend server.
- `routes/api.js` - Contains routes to handle API requests.

- Implement the following features in your backend server:


- Define routes in `routes/api.js` to handle the required endpoints for your REST API.
- Connect to the external API or retrieve data from a database as needed.
- Implement the necessary logic to process incoming requests and send back the appropriate responses.
- Enable Cross-Origin Resource Sharing (CORS) to allow your frontend client to consume the API.

3. Frontend Client (React):


- Set up the necessary packages and dependencies using Create React App or your preferred setup.
- Create the necessary components and pages to display the data from the REST API:
- `Home` - The main page/component of your application.
- Other components/pages as needed to present the data from different endpoints.

- Implement the following features in your frontend client:


- Use `axios` or a similar library to make HTTP requests to the backend API endpoints.
- Fetch and display the data from the REST API using React components and state management (e.g., `useState`, `useEffect`).
- Design the UI to present the fetched data in a user-friendly manner, such as lists, tables, or cards.
- Handle any necessary loading or error states while fetching and displaying the data.
- Implement user interactions or additional functionalities based on the requirements of your application.

4. Consuming the REST API:


- In your React components, use `axios` or a similar library to make HTTP requests to the backend API.
- Use `useEffect` to fetch the data from the API when the component mounts or when specific dependencies change.
- Store the fetched data in component state using `useState`.
- Render the data in your components, mapping over the fetched data and creating dynamic UI elements.

5. Test and Deployment:


- Test your application thoroughly, ensuring that it properly fetches and displays data from the REST API.
- Consider writing unit tests for your React components and integration tests for the backend API endpoints.
- Deploy your backend server and frontend client separately or together on a hosting platform of your choice (e.g., Heroku, AWS,
Netlify).

Remember to handle any necessary error handling, loading states, and authentication/authorization if required by the REST API.
LAB-5

Building a web application using Node.js, React, and a NoSQL database that implements server-side
rendering.
Certainly! Here's a high-level overview of building a web application using Node.js, React, and a NoSQL database that implements
server-side rendering:

1. Set up the project:


- Create a new directory for your project.
- Set up a backend server using Node.js and Express.
- Set up a frontend client using Create React App or your preferred setup.

2. Backend Server (Node.js and Express):


- Install the necessary dependencies:
```
npm install express mongoose
```

- Create the necessary files:


- `index.js` - The main entry point for your backend server.
- `routes/api.js` - Contains routes to handle API requests.
- `models/` - Directory to define your MongoDB models.

- Implement the following features in your backend server:


- Set up a MongoDB connection using Mongoose or your preferred MongoDB library.
- Define your database models using Mongoose schemas.
- Implement API routes in `routes/api.js` to handle CRUD operations (Create, Read, Update, Delete).
- Set up server-side rendering using a templating engine (e.g., EJS, Pug) or a server-side rendering framework (e.g., Next.js).
- Render the initial HTML on the server and send it to the client when requested.

3. Frontend Client (React):


- Set up the necessary packages and dependencies using Create React App or your preferred setup.
- Create the necessary components and pages to display the data from the server:
- `Home` - The main page/component of your application.
- Other components/pages as needed to present the data.

- Implement the following features in your frontend client:


- Use React components and state management (e.g., `useState`, `useEffect`) to handle UI and interactivity.
- Use `axios` or a similar library to make HTTP requests to your backend server to fetch the initial data.
- Render the initial HTML sent by the server and hydrate it with React on the client-side.
- Implement client-side rendering for subsequent interactions and updates.
- Use React Router or a similar library to handle client-side routing.

4. NoSQL Database (MongoDB):


- Set up a MongoDB database either locally or using a cloud-based service (e.g., MongoDB Atlas).
- Define your data models using Mongoose schemas in the `models/` directory of your backend server.
- Implement the necessary logic in your backend API routes to perform CRUD operations on the MongoDB database.

5. Server-side Rendering:
- Configure your backend server to render the initial HTML on the server.
- Set up a template engine (e.g., EJS, Pug) to generate the HTML templates and inject dynamic data.
- Define a server route that handles the request for the initial HTML and renders the template with the fetched data.
- Use the `renderToString` method from your chosen template engine or a server-side rendering framework (e.g., Next.js) to
generate the initial HTML.
6. Test and Deployment:
- Test your application thoroughly, including server-side rendering functionality, data retrieval from the NoSQL database, and
client-side interactivity.
- Consider writing unit tests for your backend API routes and integration tests for the server-side rendering functionality.
- Deploy your backend server and frontend client separately or together on a hosting platform of your choice (e.g., Heroku, AWS,
Netlify).
- Configure your deployment to ensure proper server-side rendering functionality.

Remember to handle any necessary error handling, loading states, and authentication/authorization if required by your
application.
LAB-7

Building a web application using Node.js, React and Webpack for asset management and
optimization.
Certainly! Here's an example of building a web application using Node.js, React, and Webpack for asset management and
optimization:

1. Set up the project:


- Create a new directory for your project.
- Initialize a new Node.js project using `npm init` and follow the prompts.
- Install the necessary dependencies:
```
npm install express react react-dom webpack webpack-cli webpack-dev-server babel-loader @babel/core @babel/preset-env
@babel/preset-react css-loader style-loader html-webpack-plugin
```

2. Create the necessary files:


- Create a `src` directory to store your application's source code.
- Inside the `src` directory, create the following files:
- `index.js` - The entry point for your React application.
- `App.js` - The main component of your application.
- `index.html` - The HTML template for your application.

3. Configure Webpack:
- Create a `webpack.config.js` file in the root directory of your project.
- Configure Webpack with the necessary loaders and plugins:
```javascript
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react'],
},
},
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
}),
],
devServer: {
contentBase: path.resolve(__dirname, 'dist'),
hot: true,
port: 3000,
},
};
```

4. Configure Babel:
- Create a `.babelrc` file in the root directory of your project.
- Configure Babel to use the necessary presets:
```json
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
```

5. Implement your React application:


- Open `index.js` and add the following code:
```javascript
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));


```

- Open `App.js` and add the following code:


```javascript
import React from 'react';

function App() {
return <h1>Hello, World!</h1>;
}

export default App;


```

- Open `index.html` and add the following code:


```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My Web Application</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
```
6. Build and run the application:
- In your project's `package.json`, add the following scripts:
```json
"scripts": {
"start": "webpack serve --mode development",
"build": "webpack --mode production"
}
```

- Run the development


LAB- 8

Building a web application using Node.js, React and Redux for state management.
Certainly! Here's an example of building a web application using Node.js, React, and Redux for state management:

1. Set up the project:


- Create a new directory for your project.
- Initialize a new Node.js project using `npm init` and follow the prompts.
- Install the necessary dependencies:
```
npm install express react react-dom redux react-redux redux-thunk
```

2. Create the necessary files:


- Create a `src` directory to store your application's source code.
- Inside the `src` directory, create the following files:
- `index.js` - The entry point for your React application.
- `App.js` - The main component of your application.
- `reducers.js` - Contains your Redux reducers.
- `actions.js` - Contains your Redux action creators.

3. Set up Redux:
- Open `reducers.js` and add the following code:
```javascript
// reducers.js
import { combineReducers } from 'redux';

// Define your initial state


const initialState = {
counter: 0,
};

// Define your reducers


const counterReducer = (state = initialState.counter, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
};

// Combine your reducers


const rootReducer = combineReducers({
counter: counterReducer,
});

export default rootReducer;


```

- Open `actions.js` and add the following code:


```javascript
// actions.js
export const increment = () => {
return {
type: 'INCREMENT',
};
};

export const decrement = () => {


return {
type: 'DECREMENT',
};
};
```

4. Implement your React application:


- Open `index.js` and add the following code:
```javascript
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import App from './App';
import rootReducer from './reducers';

const store = createStore(rootReducer, applyMiddleware(thunk));

ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
```

- Open `App.js` and add the following code:


```javascript
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './actions';

function App() {
const counter = useSelector((state) => state.counter);
const dispatch = useDispatch();

const handleIncrement = () => {


dispatch(increment());
};

const handleDecrement = () => {


dispatch(decrement());
};

return (
<div>
<h1>Counter: {counter}</h1>
<button onClick={handleIncrement}>Increment</button>
<button onClick={handleDecrement}>Decrement</button>
</div>
);
}

export default App;


```

5. Run the application:


- In your project's `package.json`, add the following script:
```json
"scripts": {
"start": "node src/index.js"
}
```

- Run the application using the command:


```
npm start
```

- Open your browser and navigate to `http://localhost:3000` to see the application running.
LAB-9

Building a web application using Node.js, React and Jest for unit testing
Certainly! Here's an example of building a web application using Node.js, React, and Jest for unit testing:

1. Set up the project:


- Create a new directory for your project.
- Initialize a new Node.js project using `npm init` and follow the prompts.
- Install the necessary dependencies:
```
npm install express react react-dom jest react-test-renderer
```

2. Create the necessary files:


- Create a `src` directory to store your application's source code.
- Inside the `src` directory, create the following files:
- `App.js` - The main component of your application.

3. Implement your React application:


- Open `App.js` and add the following code:
```javascript
import React from 'react';

function App() {
return <h1>Hello, World!</h1>;
}

export default App;


```

4. Set up Jest for testing:


- Create a `__tests__` directory in the root of your project.
- Inside the `__tests__` directory, create the following files:
- `App.test.js` - The test file for the `App` component.

5. Write unit tests:


- Open `App.test.js` and add the following code:
```javascript
import React from 'react';
import renderer from 'react-test-renderer';
import App from '../src/App';

test('renders correctly', () => {


const tree = renderer.create(<App />).toJSON();
expect(tree).toMatchSnapshot();
});
```

6. Run the tests:


- In your project's `package.json`, add the following scripts:
```json
"scripts": {
"test": "jest"
}
```

- Run the tests using the command:


```
npm test
```

- Jest will execute the tests and provide the test results.

In this example, we used Jest and `react-test-renderer` to write a unit test for the `App` component. The test renders the
component and compares the rendered output with a snapshot, ensuring that the component is rendered correctly. You can add
more tests for other components or functionalities of your web application in the respective test files.
Lab-10

Building a web application using Node.js and React that uses websockets for real-time
communication between the client and the server.

Certainly! Here's an example of building a web application using Node.js and React that uses websockets for real-time
communication between the client and the server:

1. Set up the project:


- Create a new directory for your project.
- Initialize a new Node.js project using `npm init` and follow the prompts.
- Install the necessary dependencies:
```
npm install express react react-dom socket.io
```

2. Create the necessary files:


- Create a `server.js` file for the backend server.
- Create a `client` directory for the frontend client.
- Inside the `client` directory, create the following files:
- `index.js` - The entry point for your React application.
- `App.js` - The main component of your application.

3. Implement the backend server:


- Open `server.js` and add the following code:
```javascript
const express = require('express');
const http = require('http');
const socketIO = require('socket.io');

const app = express();


const server = http.createServer(app);
const io = socketIO(server);

io.on('connection', (socket) => {


console.log('A client connected');

socket.on('message', (data) => {


console.log('Received message:', data);

// Broadcast the message to all connected clients


io.emit('message', data);
});

socket.on('disconnect', () => {
console.log('A client disconnected');
});
});

const port = 3000;


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

4. Implement the frontend client:


- Open `index.js` inside the `client` directory and add the following code:
```javascript
import React from 'react';
import ReactDOM from 'react-dom';
import io from 'socket.io-client';
import App from './App';

const socket = io('http://localhost:3000');

ReactDOM.render(
<App socket={socket} />,
document.getElementById('root')
);
```

- Open `App.js` inside the `client` directory and add the following code:
```javascript
import React, { useState, useEffect } from 'react';

function App({ socket }) {


const [message, setMessage] = useState('');
const [receivedMessage, setReceivedMessage] = useState('');

useEffect(() => {
socket.on('message', (data) => {
setReceivedMessage(data);
});
}, [socket]);

const sendMessage = () => {


socket.emit('message', message);
setMessage('');
};

return (
<div>
<input
type="text"
value={message}
onChange={(e) => setMessage(e.target.value)}
/>
<button onClick={sendMessage}>Send</button>
<p>Received message: {receivedMessage}</p>
</div>
);
}

export default App;


```

5. Run the application:


- In your project's root directory, run the command:
```
node server.js
```
- Open a browser and navigate to `http://localhost:3000` to see the application running.

- You can open multiple browser tabs/windows to test the real-time communication by entering messages in one client and
seeing them appear in all connected clients.

In this example, we used the `socket.io` library to enable real-time communication between the client and the server. The server
listens for socket connections and handles events such as receiving and broadcasting messages. The client establishes a socket
connection to the server and sends
Lab-11

Building a web application using Node.js, React, and a NoSQL database that implements server-side
rendering
Certainly! Here's an example of building a web application using Node.js, React, and a NoSQL database (MongoDB) that
implements server-side rendering:

1. Set up the project:


- Create a new directory for your project.
- Initialize a new Node.js project using `npm init` and follow the prompts.
- Install the necessary dependencies:
```
npm install express react react-dom mongoose
```

2. Create the necessary files:


- Create a `server.js` file for the backend server.
- Create a `client` directory for the frontend client.
- Inside the `client` directory, create the following files:
- `index.js` - The entry point for your React application.
- `App.js` - The main component of your application.

3. Implement the backend server:


- Open `server.js` and add the following code:
```javascript
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const App = require('./client/App');

// Connect to MongoDB
mongoose.connect('mongodb://localhost/my_database', {
useNewUrlParser: true,
useUnifiedTopology: true,
});

const app = express();

// Serve static files from the 'client' directory


app.use(express.static(path.join(__dirname, 'client')));

// Define a route for server-side rendering


app.get('/', (req, res) => {
// Fetch data from the database
const data = {
title: 'Hello, World!',
message: 'Welcome to my web application!',
};

// Render the React application to HTML


const html = ReactDOMServer.renderToString(
<App title={data.title} message={data.message} />
);
// Send the rendered HTML to the client
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>${data.title}</title>
</head>
<body>
<div id="root">${html}</div>
<script src="/bundle.js"></script>
</body>
</html>
`);
});

const port = 3000;


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

4. Implement the frontend client:


- Open `index.js` inside the `client` directory and add the following code:
```javascript
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.hydrate(<App />, document.getElementById('root'));


```

- Open `App.js` inside the `client` directory and add the following code:
```javascript
import React from 'react';

function App({ title, message }) {


return (
<div>
<h1>{title}</h1>
<p>{message}</p>
</div>
);
}

export default App;


```

5. Run the application:


- Start your local MongoDB server.
- In your project's root directory, run the command:
```
node server.js
```
Lab-12

Building a web application using Node.js and React that consumes data from a REST API.
Certainly! Here's an example of building a web application using Node.js and React that consumes data from a REST API:

1. Set up the project:


- Create a new directory for your project.
- Initialize a new Node.js project using `npm init` and follow the prompts.
- Install the necessary dependencies:
```
npm install express react react-dom axios
```

2. Create the necessary files:


- Create a `server.js` file for the backend server.
- Create a `client` directory for the frontend client.
- Inside the `client` directory, create the following files:
- `index.js` - The entry point for your React application.
- `App.js` - The main component of your application.

3. Implement the backend server:


- Open `server.js` and add the following code:
```javascript
const express = require('express');
const axios = require('axios');

const app = express();

// Define a route to fetch data from the REST API


app.get('/api/data', async (req, res) => {
try {
// Make a request to the REST API
const response = await axios.get('https://api.example.com/data');
const data = response.data;

// Send the data to the client


res.json(data);
} catch (error) {
// Handle error
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
});

const port = 3000;


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

4. Implement the frontend client:


- Open `index.js` inside the `client` directory and add the following code:
```javascript
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
```

- Open `App.js` inside the `client` directory and add the following code:
```javascript
import React, { useEffect, useState } from 'react';
import axios from 'axios';

function App() {
const [data, setData] = useState([]);

useEffect(() => {
// Fetch data from the server
const fetchData = async () => {
try {
const response = await axios.get('/api/data');
setData(response.data);
} catch (error) {
console.error(error);
}
};

fetchData();
}, []);

return (
<div>
<h1>Data from REST API:</h1>
<ul>
{data.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}

export default App;


```

5. Run the application:


- In your project's root directory, run the command:
```
node server.js
```

- Open a browser and navigate to `http://localhost:3000` to see the web application consuming data from the REST API.

In this example, the backend server defines a route `/api/data` that fetches data from a REST API using the `axios` library. The
frontend client, implemented with React, makes a request to the backend server to retrieve the data and renders it in a list
format.

Lab-13
Building a web application using Node.js, React and Webpack for asset management and optimization
Sure! I can provide you with a basic setup for building a web application using Node.js, React, and Webpack. This setup will help
you with asset management and optimization. Here are the steps:

Step 1: Set up the project

1. Create a new directory for your project:


```
mkdir my-app
cd my-app
```

2. Initialize a new Node.js project and install the required dependencies:


```
npm init -y
npm install react react-dom
npm install --save-dev webpack webpack-cli webpack-dev-server html-webpack-plugin babel-loader @babel/core @babel/preset-
env @babel/preset-react
```

Step 2: Configure Webpack

1. Create a file named `webpack.config.js` in the root of your project directory and add the following configuration:
```javascript
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react'],
},
},
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
}),
],
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 3000,
},
};
```

Step 3: Create React components

1. Create a new directory named `src` in the root of your project directory:
```
mkdir src
```

2. Create a file named `index.js` inside the `src` directory and add the following code:
```javascript
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));


```

3. Create a file named `App.js` inside the `src` directory and add a simple React component:
```javascript
import React from 'react';

const App = () => {


return <h1>Hello, World!</h1>;
};

export default App;


```

4. Create a file named `index.html` in the root of your project directory and add the following code:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
```

Step 4: Build and run the application

1. Open the `package.json` file and add the following scripts under the `"scripts"` section:
```json
"scripts": {
"start": "webpack serve --mode development --open",
"build": "webpack --mode production"
}
```

2. Run the development server:


```
npm start
```

This will start the development server on `http://localhost:3000` and automatically open it in your default browser. You should
see "Hello, World!" displayed on the page.

3. To build the production-ready version of your application, run:


```
npm run build
```

This will generate an optimized bundle in the `dist` directory.

That's it! You now have a basic setup for building


Lab- 14

Building a web application using Node.js and React that uses the latest features of ECMAScript and
Label with code

Certainly! To build a web application using Node.js and React with the latest features of ECMAScript and Babel, follow these
steps:

Step 1: Set up the project

1. Create a new directory for your project:


```
mkdir my-app
cd my-app
```

2. Initialize a new Node.js project and install the required dependencies:


```
npm init -y
npm install react react-dom
npm install --save-dev webpack webpack-cli webpack-dev-server html-webpack-plugin @babel/core @babel/preset-env
@babel/preset-react babel-loader
```

Step 2: Configure Babel

1. Create a file named `.babelrc` in the root of your project directory and add the following configuration:
```json
{
"presets": [
["@babel/preset-env", {
"targets": {
"node": "current"
}
}],
"@babel/preset-react"
]
}
```

Step 3: Configure Webpack

1. Create a file named `webpack.config.js` in the root of your project directory and add the following configuration:
```javascript
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
}),
],
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 3000,
},
};
```

Step 4: Create React components

1. Create a new directory named `src` in the root of your project directory:
```
mkdir src
```

2. Create a file named `index.js` inside the `src` directory and add the following code:
```javascript
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));


```

3. Create a file named `App.js` inside the `src` directory and add a simple React component using the latest ECMAScript features:
```javascript
import React, { useState } from 'react';

const App = () => {


const [count, setCount] = useState(0);

const increment = () => {


setCount(count + 1);
};

return (
<div>
<h1>Hello, World!</h1>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
};

export default App;


```

4. Create a file named `index.html` in the root of your project directory and add the following code:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
```

Step 5: Build and run the application

1. Open the `package.json` file and add the following scripts under the `"scripts"` section:
```json
"scripts": {
"start": "webpack serve --mode development

You might also like