{"id":274,"date":"2020-06-05T10:32:37","date_gmt":"2020-06-05T01:32:37","guid":{"rendered":"https:\/\/blog.wsd.sh\/?p=274"},"modified":"2020-06-05T10:34:53","modified_gmt":"2020-06-05T01:34:53","slug":"nodejs-book-chapter-5","status":"publish","type":"post","link":"https:\/\/blog.wsd.sh\/?p=274","title":{"rendered":"Nodejs Book: Chapter 5"},"content":{"rendered":"<p>So now that we have a basic working file server up and running, if we want<br \/>\nto make a web application, that entails doing more than serving static files.<br \/>\nHow can we make requests from a client page and have the server perform some<br \/>\nkind of task relevant to the request.<\/p>\n<p>In the first chapter of this book we established that URL&#8217;s are effectively<br \/>\njust a string that is passed into a server and that we had to give it meaning.<br \/>\nOne of the meanings that we gave it was that of a file path as we build a file<br \/>\nserver. But we can also give URL&#8217;s other meanings like calling logic, we just<br \/>\nhave to decide on a url-base to distinguish what logic we want executed on the<br \/>\nserver.<\/p>\n<p>Basically all we need to do is decide upon a unique URL that doesn&#8217;t overwrite<br \/>\nother potential calls to the server. We can decide on &#8220;\/api&#8221;, or &#8220;\/callback&#8221;,<br \/>\nor &#8220;\/node&#8221;, &#8220;\/rest&#8221; or otherwise as long as it doesn&#8217;t overwrite a file path.<br \/>\nMy personal preference is to use the base of &#8220;\/api&#8221;.<\/p>\n<p>The file layout of this chapter&#8217;s code is listed below.<\/p>\n<pre>- api.js\n+ public\/\n| - get.html\n| - + js\/\n| --- get.js\n<\/pre>\n<p>File: get.html<\/p>\n<pre>&lt;!DOCTYPE HTML&gt;\n&lt;html&gt;\n\n    &lt;head&gt;\n\n        &lt;meta charset=\"utf-8\"\/&gt;\n        &lt;title&gt;Ajax Request&lt;\/title&gt;\n\n    &lt;\/head&gt;\n\n    &lt;body&gt;\n\n        &lt;button id=\"clickBtn\"&gt;Click Me!&lt;\/button&gt;\n        &lt;p id=\"responseText\"&gt;&lt;\/p&gt;\n\n        &lt;script type=\"text\/javascript\" src=\"js\/get.js\"&gt;&lt;\/script&gt;\n\n    &lt;\/body&gt;\n\n&lt;\/html&gt;\n<\/pre>\n<p>File: js\/get.js<\/p>\n<pre>\"use strict\";\n\nvar clickBtn = document.getElementById(\"clickBtn\");\nvar responseText = document.getElementById(\"responseText\");\n\nclickBtn.addEventListener(\"click\", function (event) {\n\n    var xml = new XMLHttpRequest();\n    xml.open(\"GET\", \"\/api\/hello\", true);\n    xml.send();\n\n    xml.onload = function() {\n\n        responseText.textContent = xml.responseText;\n\n    }\n\n\n});\n<\/pre>\n<p>File: api.js<\/p>\n<pre>\"use strict\";\n\nconst http = require(\"http\");\nconst handleFile = require(\"handle-file\");\n\nconst server = http.createServer();\nserver.on(\"request\", handleRequest);\nserver.listen(8080, handleListen);\n\nfunction handleRequest(req, res) {\n\n    switch(req.url) {\n        case \"\/api\/hello\":\n\n            res.writeHead(200, { \"Content-Type\" : \"text\/plain\" });\n            res.end(\"Hello, World!\");\n\n        break;\n        default:\n\n            handleFile(req, res);\n\n        break;\n    }\n\n}\n\nfunction handleListen( ) {\n\n    console.log(\"Server is listening on port 8080\");\n\n}\n<\/pre>\n<p>When we run our server and click on the button we should now see the following<br \/>\noutput:<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/blog.wsd.sh\/wp-content\/uploads\/2020\/06\/fig_07-300x233.jpg\" alt=\"\" class=\"alignnone size-medium wp-image-275\" width=\"300\" height=\"233\" srcset=\"https:\/\/blog.wsd.sh\/wp-content\/uploads\/2020\/06\/fig_07-300x233.jpg 300w, https:\/\/blog.wsd.sh\/wp-content\/uploads\/2020\/06\/fig_07-1024x795.jpg 1024w, https:\/\/blog.wsd.sh\/wp-content\/uploads\/2020\/06\/fig_07-768x596.jpg 768w, https:\/\/blog.wsd.sh\/wp-content\/uploads\/2020\/06\/fig_07.jpg 1141w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/p>\n<p>Hopefully the code is in this chapter should be pretty self explanatory, but let&#8217;s<br \/>\ntake a look at two parts. The first part being the request sent from the client.<\/p>\n<pre>var xml = new XMLHttpRequest();\nxml.open(\"GET\", \"\/api\/hello\", true);\nxml.send();\n\nxml.onload = function() {\n\n    responseText.textContent = xml.responseText;\n\n}\n<\/pre>\n<p>While web pages have become much more dynamic, for a long period of time, web pages<br \/>\nwere a static fair. A page was served with a list of hyperlinks, and hyperlinks<br \/>\ncould be clicked to navigate to another page. It was assumed that any requests to<br \/>\nthe server were for a different page. As content on the internet became more dynamic<br \/>\n&#8220;Ajax&#8221; became a common implementation of sending information to and from the server<br \/>\nfrom within Javascript.<\/p>\n<p>&#8220;Ajax&#8221; stands for &#8220;Asynchronous JSON and XML&#8221; request. And it&#8217;s exactly the same<br \/>\nas a browser requesting a page, just performed from within Javascript and without<br \/>\nthe page being reloaded. In this case we send a &#8220;GET&#8221; request to the url &#8220;\/api\/hello&#8221;<br \/>\nand once it&#8217;s loaded we display the response text to the user.<\/p>\n<pre>function handleRequest(req, res) {\n\n    switch(req.url) {\n        case \"\/api\/hello\":\n\n            res.writeHead(200, { \"Content-Type\" : \"text\/plain\" });\n            res.end(\"Hello, World!\");\n\n        break;\n        default:\n\n            handleFile(req, res);\n\n        break;\n    }\n\n}\n<\/pre>\n<p>For our server, our api.js only has one minor change from the previous chapter.<br \/>\nWe&#8217;ve added a switch statement to the request url, giving preference to logical<br \/>\nfunctions we define and defaulting to serving a file if none of the patterns match.<\/p>\n<p>This was a basic example of testing waters with ajax. And is not very useful yet.<br \/>\nWe will continue expanding this example in the next few chapters as we cover sending<br \/>\nand receiving JSON data in the next chapter.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In the previous chapter we learned how to create modules to simplify our code. Now that he have a basic grasp on how to serve static files from Nodejs, in this chapter we switch to more learning how to create a more dynamic application server where we handle both static files, and Ajax requests from the client. We start with a simple &#8220;hello world&#8221; example. <\/p>\n","protected":false},"author":1,"featured_media":249,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_mi_skip_tracking":false},"categories":[4],"tags":[],"_links":{"self":[{"href":"https:\/\/blog.wsd.sh\/index.php?rest_route=\/wp\/v2\/posts\/274"}],"collection":[{"href":"https:\/\/blog.wsd.sh\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.wsd.sh\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.wsd.sh\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.wsd.sh\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=274"}],"version-history":[{"count":2,"href":"https:\/\/blog.wsd.sh\/index.php?rest_route=\/wp\/v2\/posts\/274\/revisions"}],"predecessor-version":[{"id":277,"href":"https:\/\/blog.wsd.sh\/index.php?rest_route=\/wp\/v2\/posts\/274\/revisions\/277"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blog.wsd.sh\/index.php?rest_route=\/wp\/v2\/media\/249"}],"wp:attachment":[{"href":"https:\/\/blog.wsd.sh\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=274"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.wsd.sh\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=274"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.wsd.sh\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=274"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}