Created
April 16, 2019 15:21
-
-
Save tghimanshu/b98090241808e7679ec4ac807380d444 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// core node modules | |
const http = require('http'); | |
const fs = require('fs'); | |
// creating a server | |
const server = http.createServer((req, res) => { | |
let url = req.url; | |
let method = req.method; | |
// for content in home page | |
if (url === '/') { | |
res.setHeader('Content-Type', 'text/html'); | |
res.write('<form action="/message" method="POST"><input type="text" name="message"><button type="submit">Submit</button></form>'); | |
return res.end(); | |
} | |
// For Post requested Message Page | |
if (url === "/message" && method === "POST") { | |
const body = []; | |
// get data and working on it | |
req.on('data', chunk => { | |
// console.log(chunk); | |
body.push(chunk); | |
}); // res on data | |
return req.on('end', () => { | |
// convert to readable | |
let parsedBody = Buffer.concat(body).toString(); | |
// splitting and retriving the value of input | |
let message = parsedBody.split('=')[1]; | |
// console.log(message); | |
fs.writeFile('message.txt', message, err => { | |
// redirect code | |
res.statusCode = 302; | |
res.setHeader('Location', '/'); | |
// always return response end so it stop execution | |
return res.end(); | |
});//fs write code ends | |
});// res ends | |
}// message page code ends | |
// if nothing matches underneath code executes | |
res.setHeader('Content-Type', 'text/html'); | |
res.write('<html>'); | |
res.write('<head><title>Hello World!</title></head>'); | |
res.write('<body'); | |
res.write('<h1>Hello From My Node Server!</h1>'); | |
res.write('</body>'); | |
res.write('</html>'); | |
return res.end(); | |
}); | |
// To keep server running at port 3000 | |
server.listen(3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment