How to do it…

Let's write some simple code to process a request, and just show what was asked. Our main code for the request process will be the following:

// Source file: src/process_request.js

const http = require("http");

http
.createServer((req, res) => {
// For PUT/POST methods, wait until the
// complete request body has been read.

if (req.method === "POST" || req.method === "PUT") {
let body = "";

req.on("data", data => {
body += data;
});

req.on("end", () => processRequest(req, res, body));

} else {
return processRequest(req, res, "");
}
})
.listen(8080, "localhost");

// continues...

The processRequest() function will be quite simple, limited to showing its parameters. This kind of code can become helpful if you need to better understand how to process requests, as we'll see in the next chapter. We will get parameters both from the URL and the request body:

// ...continued

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

function processRequest(req, res, body) {
/*
Get parameters, both from the URL and the request body
*/
const urlObj = url.parse(req.url, true);
const urlParams = urlObj.query;
const bodyParams = querystring.parse(body);

console.log("URL OBJECT", urlObj);
console.log("URL PARAMETERS", urlParams);
console.log("BODY PARAMETERS", bodyParams);

/*
Here you would analyze the URL to decide what is required
Then you would do whatever is needed to fulfill the request
Finally, when everything was ready, results would be sent
In our case, we just send a FINISHED message
*/

res.writeHead(200, "OK");
res.end(`FINISHED WITH THE ${req.method} REQUEST`);
}

The output of this code, which we'll see next, will be the the request url object (req.url), its parameters, and the parameters in the body.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.77.4