FSD-1 slip 9:Slip9 Create a Node.js file that writes an HTML form, with a concatenate two string.
const http = require('http');
const { parse } = require('querystring');
const server = http.createServer((req, res) => {
if (req.method === 'GET') {
// 1. Serve the HTML Form
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<h2>String Concatenator</h2>
<form method="POST">
<input type="text" name="str1" placeholder="First string" required><br><br>
<input type="text" name="str2" placeholder="Second string" required><br><br>
<button type="submit">Concatenate</button>
</form>
`);
}
else if (req.method === 'POST') {
// 2. Handle the Form Submission
let body = '';
// Data comes in chunks (streams)
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
const formData = parse(body);
const result = formData.str1 + formData.str2;
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(`
<h3>Result: ${result}</h3>
<a href="/">Go Back</a>
`);
});
}
});
server.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});
Comments
Post a Comment