Skip to content

Instantly share code, notes, and snippets.

@yhoon3002
Created April 9, 2024 11:32
const http = require("http");
const fs = require('fs');
const server = http.createServer((req, res) => {
const url = req.url;
const method = req.method;
if(url === '/') {
res.write('<html>');
res.write('<head><title>Enter Message</title></head>');
res.write('<body><form action="/message" method="POST"><input type="text" name="message"><button type="submit">Send</button></form></body>');
res.write('</html>');
return res.end();
}
if (url === '/message' && method === 'POST') {
const body = [];
req.on('data', (chunk) => {
console.log(chunk);
body.push(chunk);
});
req.on('end', () => {
const parsedBody = Buffer.concat(body).toString();
const message = parsedBody.split("=")[1];
fs.writeFileSync('message.txt', message);
});
res.statusCode = 302;
res.setHeader('Location', '/');
return res.end();
}
res.setHeader('Content-Type', 'text/html');
res.write('<html>');
res.write('<head><title>First Node.js</title></head>');
res.write('<body><h1>Hello Node.js</h1></body>');
res.write('</html>');
res.end();
});
server.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment