Augment Server to Long Requests

We just saw a server logging request parameters on the console. You may know from HTML5 that form data may be sent by using method="GET" as in the example, or as Method="POST" data. Both ways the length of the data of the request may be long. To cater for arbitrary length data, we must adapt the server code. Look at the following.

Example 16.4. Augmented Server Code, myg53/main.js
"use strict";

const http = require("http");
const httpStatus = require("http-status-codes");
const hostname = "127.0.0.1";
const port = 3000;
const app = http.createServer();            // server as an obj

const getJSONString = function (obj) {      // prettyprint obj
    return JSON.stringify(obj, null, 4);
}

app.on("request", function (req, res) {     // eventhandler for "request"
    let body = [];
    req.on("data", function (bodyData) {    // eventhandling for data reception
        body.push(bodyData);                // bodyData is an object
    });
    req.on("end", function () {             // eventhandling for end-of-data
        body = Buffer.concat(body).toString();
        console.log("Log: Request Body Contents: " + body);
    });

    console.log("Log: Method: " + req.method);
    console.log("Log: URL: " + getJSONString(req.url));
    console.log("Log: Headers:\n" + getJSONString(req.headers));
                                            // prep response header
    res.writeHead(httpStatus.OK, {
        "Content-Type": "text/html; charset=utf-8"
    });
                                            // prep response body
    let responseMsg = "<h1>Kilroy Was Here Too</h1>";
    responseMsg += "<p><kbd>myg53</kbd> is helping him</p>";
    res.write(responseMsg);                 // respond
    res.end();                              // sends response http
});

app.listen(port, hostname, function () {
    console.log(`Server running, and listening at http://${hostname}:${port}/`);
});

On your CLI do npm test. Then go to your browser and do http://localhost:3000. Check the server's log.


Now we create an index.html file:

Example 16.5. Client Page with Form, myg53/index.html
<!doctype html>
<html>
    <head>
        <meta charset='utf-8'/>
        <title>Second Server Test Data with POST</title>

    </head>
    <body>
        <h1>Second Server Test Data with POST</h1>
        <form method="post" action="http://localhost:3000/">
            Name: <input type="test" name="name"/>
            Password: <input type="password" name="password"/>
            <input type="submit" value="send"/>
        </form>
    </body>
</html>

On your CLI do npm test. Then go to your browser and paste the path to myg53/index.html eg file:///home/nml/nodeMyGPNode/myg53/index.html into your browsers url. There's a reason why you cannot use the HTTP protocol and localhost here. Can you spot it? Fill in the form and submit. Then check the server's log.