Goal:
The goal is to render data from the form where you enter your name and band. Once you submit you will be redirected to a new page which will state
Name: John Doe
Favorite Band: The Who
Problem:
I cannot use the express module for this exercise and I got it to render the data but it comes out like this on the page:
Your name is: name=John+Doe&band=The+Who
Your favorite band is: name=John+Doe&band=The+Who
I do realize that I am looking for something like body.name and body.band but I keep getting error messages.
What I have tried:
I have tried body-parser and query string but most of the examples I have found in researching have all dealt with being able to use express I am struggling with the translation.
What I am asking for:
I just need some guidance on how to solve this.
Here is my html file:
<!DOCTYPE html>
<html>
<head>
<title>Welcome to my post form!</title>
</head>
<body>
<div class='container'>
<div class='jumbotron text-center'>
<h1>Please post using this form:</h1>
</div>
<div class="row">
<div class="col-sm-12 text-center">
<form action="http://localhost:3000/thanks" method="POST">
<input name="name" placeholder="enter your name">
<input name="band" placeholder="enter your favorite band">
<button type='submit'>submit</button>
</form>
</div>
</div>
</div>
</body>
</html>
Here is my server.js file and what I currently have that works but gives me the output I showed above:
let http = require('http');
let fs = require('fs');
let server = http.createServer(handleRequest);
const port = process.env.PORT || 3000;
function handleRequest(req, res) {
var path = req.url;
if (req.method === "GET"){
res.writeHead(200, {"Content-Type": "text/html"});
fs.createReadStream("postalServiceHTML.html", "UTF-8").pipe(res);
} else if (req.method === "POST" && path == '/thanks'){
var body = "";
req.on("data", function(chunk){
body += chunk;
});
}
req.on("end", function(){
res.writeHead(200, {"Content-Type": "text/html"})
res.end(`
<!DOCTYPE HTML>
<html>
<head>
<title> Form Results </title>
</head>
<body>
<h1> Your Form Results </h1>
<p> Your name is: ${body} </p>
<p> Your favorite band is: ${body} </p>
</body>
</html>
`);
});
}
server.listen(port, () => console.log(Server is running on port ${port}));