Share
Explore

Visualize and understand how data sent from the client is processed and represented in the `req` object on the server side in an Express.js application.

### HTML and JavaScript to Present a Route and Print the req Object Contents
The following example demonstrates how to create a route that prints out the contents of the `req` object in an Express.js application. The HTML and JavaScript will allow you to submit data to this route and display the server's response.

Backend: Node.js Server (server.js)

1. **Create `server.js`**:
```javascript const express = require('express'); const app = express(); const port = 3000;
// Middleware to parse URL-encoded bodies and JSON app.use(express.urlencoded({ extended: true })); app.use(express.json());
// Serve static files app.use(express.static('public'));
// Route to print out the req object app.post('/print-req', (req, res) => { res.json(req); });
// Start the server app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); }); ```

Frontend: HTML and JavaScript

2. **Create the folder structure**: - `public` - `index.html` - `style.css` - `script.js`
3. **Create `index.html`**:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Express req Object Viewer</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="container"> <h1>Express req Object Viewer</h1> <form id="reqForm"> <label for="name">Name:</label> <input type="text" id="name" name="name" required> <label for="email">Email:</label> <input type="email" id="email" name="email" required> <button type="submit">Submit</button> </form> <pre id="reqOutput"></pre> </div> <script src="script.js"></script> </body> </html>

4. Create `style.css`

```css body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; }
.container { max-width: 600px; margin: 50px auto; padding: 20px; background-color: white; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); border-radius: 8px; }
h1 { text-align: center; color: #333; }
form { display: flex; flex-direction: column; }
label { margin-top: 10px; }
input { padding: 8px; margin-top: 5px; }
button { padding: 10px; margin-top: 20px; background-color: #28a745; color: white; border: none; border-radius: 4px; cursor: pointer; }
button:hover { background-color: #218838; }
pre { background-color: #f8f8f8; padding: 15px; border-radius: 5px; margin-top: 20px; overflow-x: auto; } ```

5. Create `script.js`

document.getElementById('reqForm').addEventListener('submit', function(event) { event.preventDefault();
const formData = new FormData(this); const formObject = {}; formData.forEach((value, key) => { formObject[key] = value; });
fetch('/print-req', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formObject) }) .then(response => response.json()) .then(data => { document.getElementById('reqOutput').textContent = JSON.stringify(data, null, 2); }) .catch(error => console.error('Error:', error)); });
### Explanation
- **Backend (server.js)**: - The server has a route `/print-req` that responds with the contents of the `req` object in JSON format. - The middleware is set up to parse URL-encoded bodies and JSON.
- **Frontend (index.html, style.css, script.js)**: - `index.html` contains a form for the user to submit their name and email. - `style.css` provides basic styling to make the form look presentable. - `script.js` handles the form submission using the Fetch API to send the form data as a JSON object to the server and then displays the server's response (which includes the `req` object) in a `<pre>` tag.
By using this setup, students can visualize and understand how data sent from the client is processed and represented in the `req` object on the server side in an Express.js application.

megaphone

Final version:

To properly test the application, you should follow these steps:
Navigate to the Root URL:
Open your browser and go to http://localhost:3000.
This should display the form where you can enter your name and email.
Fill Out and Submit the Form:
Enter your name and email in the form fields.
Click the "Submit" button to send the form data to the /print-req route using a POST request.
Here is a summary of what you need to do:

Access the Form

Open your browser and go to http://localhost:3000.
You should see the form as described in the previous instructions.

Fill Out and Submit the Form

Enter your name and email in the form fields.
Click the "Submit" button.

Review the Response

The JavaScript on the client side will handle the form submission.
It will send the form data as a JSON object to the /print-req route using a POST request.
The server will respond with the contents of the req object, which will be displayed in the <pre> element on the page.

Example: Correct Workflow

Go to: http://localhost:3000 in your web browser.
Fill in the form with your name and email.
Submit the form by clicking the "Submit" button.
Here is an additional check to ensure everything is set up correctly:

Ensure All Files Are Correct

server.js: Back End File
const express = require('express');
const app = express();
const port = 3000;

// Middleware to parse URL-encoded bodies and JSON
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

// Serve static files
app.use(express.static('public'));

// Route to print out the req object
app.post('/print-req', (req, res) => {
res.json(req); // Responds with the entire req object as JSON
});

// Start the server
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});

public/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Express req Object Viewer</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>Express req Object Viewer</h1>
<form id="reqForm">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<button type="submit">Submit</button>
</form>
<pre id="reqOutput"></pre>
</div>
<script src="script.js"></script>
</body>
</html>

public/style.css:
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}

.container {
max-width: 600px;
margin: 50px auto;
padding: 20px;
background-color: white;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
}

h1 {
text-align: center;
color: #333;
}

form {
display: flex;
flex-direction: column;
}

label {
margin-top: 10px;
}

input {
padding: 8px;
margin-top: 5px;
}

button {
padding: 10px;
margin-top: 20px;
background-color: #28a745;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}

button:hover {
background-color: #218838;
}

pre {
background-color: #f8f8f8;
padding: 15px;
border-radius: 5px;
margin-top: 20px;
overflow-x: auto;
}

public/script.js:
document.getElementById('reqForm').addEventListener('submit', function(event) {
event.preventDefault(); // Prevent the default form submission

const formData = new FormData(this); // Collect form data
const formObject = {};
formData.forEach((value, key) => {
formObject[key] = value; // Convert FormData to JSON object
});

fetch('/print-req', {
method: 'POST',
headers: {
'Content-Type': 'application/json' // Set content type to JSON
},
body: JSON.stringify(formObject) // Send JSON object to server
})
.then(response => response.json()) // Parse the JSON response from the server
.then(data => {
document.getElementById('reqOutput').textContent = JSON.stringify(data, null, 2); // Display the req object in a preformatted text
})
.catch(error => console.error('Error:', error)); // Handle any errors
});

Make sure all files are correctly placed and contain the correct code.
If everything is set up correctly, navigating to http://localhost:3000, filling out the form, and submitting it should work as expected.
4o
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.