Created
March 15, 2019 18:22
-
-
Save rajatk16/206b2a62b1d4dc771731e94e71bf5842 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs'); | |
const requestHandler = (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); | |
}); | |
return req.on('end', () => { | |
const parsedBody = Buffer.concat(body).toString(); | |
const message = parsedBody.split('=')[1]; | |
fs.writeFile('message.txt', message, err => { | |
res.statusCode = 302; | |
res.setHeader('Location', '/'); | |
return res.end(); | |
}); | |
}); | |
} | |
res.setHeader('Content-Type', 'text/html'); | |
res.write('<html>'); | |
res.write('<head><title>My First Page</title><head>'); | |
res.write('<body><h1>Hello from my Node.js Server!</h1></body>'); | |
res.write('</html>'); | |
res.end(); | |
}; | |
exports.handler = requestHandler; | |
exports.someText = 'Go To https://localhost:3000'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment