const http = require("http");
const querystring = require("querystring");

const PORT = 3000;

function requestListener(request, response) {
    console.log("method:  " + request.method);
    console.log("URL:     " + request.url);
    console.log("headers: " + JSON.stringify(request.headers));

    if (request.method === "POST"){
        let body = "";
        request.on("data", chunk => {
            body += chunk;
        });
        request.on("end", () => {
            console.log("Final body:", body);
            let formData = querystring.parse(body);
            console.log("Name:    " + formData.name);
            console.log("Email:   " + formData.email);
            console.log("Message: " + formData.message);

            // Send back an acknowledgement
            response.end("Thank you for your message.");
        });
    }
    else // send back nothing if it wasn't a POST
        response.end();
}
    
http.createServer(requestListener).listen(PORT);
console.log(`Server running at http://localhost:${PORT}`);
