Skip to content
Snippets Groups Projects
Commit 866406b4 authored by Oshani Weerakoon's avatar Oshani Weerakoon
Browse files

Exercise 8 + Instructions

parent 4c58c3b4
Branches
No related tags found
No related merge requests found
We'll use Node.js for the server and Express to handle HTTP requests. On the client side, we'll use vanilla JavaScript to gather form data and send it to the server.
**Backend Setup:**
1. Install Node.js from [nodejs.org](https://nodejs.org/).
2. Set up your project directory and install Express:
```bash
mkdir my_project
cd my_project
npm init -y
npm install express body-parser
```
3. Create a file named `server.js` and add the following code to set up an Express server that can handle POST requests:
```javascript
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
app.use(bodyParser.json());
app.post('/updateProfile', (req, res) => {
// Imagine we're receiving a batched request with profile information
const { personalInfo, preferences } = req.body;
// Here you would handle the data, e.g., update the database
console.log('Personal Information:', personalInfo);
console.log('Preferences:', preferences);
// Send a response back to the client
res.json({ status: 'success', message: 'Profile updated successfully!' });
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
```
**Frontend Setup:**
1. In your project directory, create a folder named `public` and add two files: `index.html` and `script.js`.
2. In `index.html`, create a simple form for the user profile and preferences:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Batch Data Transmission Example</title>
</head>
<body>
<form id="profileForm">
<h2>Profile Information</h2>
<input type="text" id="name" placeholder="Name">
<input type="email" id="email" placeholder="Email">
<h2>Preferences</h2>
<label>
<input type="checkbox" id="newsletter"> Subscribe to newsletter
</label>
<button type="button" id="updateButton">Update Profile</button>
</form>
<script src="script.js"></script>
</body>
</html>
```
3. In `script.js`, add JavaScript to handle the form submission and batch the data:
```javascript
document.addEventListener('DOMContentLoaded', () => {
const updateButton = document.getElementById('updateButton');
updateButton.addEventListener('click', () => {
const personalInfo = {
name: document.getElementById('name').value,
email: document.getElementById('email').value
};
const preferences = {
newsletter: document.getElementById('newsletter').checked
};
// Batch the data into a single object
const batchedData = { personalInfo, preferences };
// Send the batched data to the server
fetch('/updateProfile', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(batchedData)
})
.then(response => response.json())
.then(data => {
console.log(data);
alert('Profile updated successfully!');
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred while updating the profile.');
});
});
});
```
**Testing the Setup:**
1. Serve the `public` folder using `http-server`:
```bash
cd path/to/your/project-directory
npx http-server public -p 8080
```
2. Run the server using:
```bash
node server.js
```
3. Open your web browser and navigate to `http://localhost:8080`. You should see your form.
4. Fill out the form and click the "Update Profile" button. The JavaScript code will batch the form data into a single object and send it to the server in one POST request.
5. The server will log the received data to the console and send a success message back to the client, which will alert the user.
This example demonstrates how you can combine multiple pieces of data into a single network request, reducing the number of requests and potentially lowering the energy consumption associated with network traffic.
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Batch Data Transmission Example</title>
</head>
<body>
<form id="profileForm">
<h2>Profile Information</h2>
<input type="text" id="name" placeholder="Name">
<input type="email" id="email" placeholder="Email">
<h2>Preferences</h2>
<label>
<input type="checkbox" id="newsletter"> Subscribe to newsletter
</label>
<button type="button" id="updateButton">Update Profile</button>
</form>
<script src="script.js"></script>
</body>
</html>
document.addEventListener('DOMContentLoaded', () => {
const updateButton = document.getElementById('updateButton');
updateButton.addEventListener('click', () => {
const personalInfo = {
name: document.getElementById('name').value,
email: document.getElementById('email').value
};
const preferences = {
newsletter: document.getElementById('newsletter').checked
};
// Batch the data into a single object
const batchedData = { personalInfo, preferences };
// Send the batched data to the server
fetch('/updateProfile', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(batchedData)
})
.then(response => response.json())
.then(data => {
console.log(data);
alert('Profile updated successfully!');
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred while updating the profile.');
});
});
});
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
app.use(bodyParser.json());
app.post('/updateProfile', (req, res) => {
// Imagine we're receiving a batched request with profile information
const { personalInfo, preferences } = req.body;
// Here you would handle the data, e.g., update the database
console.log('Personal Information:', personalInfo);
console.log('Preferences:', preferences);
// Send a response back to the client
res.json({ status: 'success', message: 'Profile updated successfully!' });
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment