{"id":296,"date":"2020-06-12T16:15:09","date_gmt":"2020-06-12T07:15:09","guid":{"rendered":"https:\/\/blog.wsd.sh\/?p=296"},"modified":"2020-06-12T16:17:12","modified_gmt":"2020-06-12T07:17:12","slug":"nodejs-book-chapter-9","status":"publish","type":"post","link":"https:\/\/blog.wsd.sh\/?p=296","title":{"rendered":"Nodejs Book: Chapter 9"},"content":{"rendered":"<p>In the previous chapter we uploaded form data and returned the raw string. In<br \/>\nthis chapter, we will continue to expand on the last chapter by converting the<br \/>\ndata from the uploading form into a JSON string. Lets take a look at the string<br \/>\nwe returned to the client.<\/p>\n<pre>-----------------------------2285823208496\nContent-Disposition: form-data; name=\"username\"\n\nmy_username\n-----------------------------2285823208496\nContent-Disposition: form-data; name=\"email\"\n\nmy_email@example.com\n-----------------------------2285823208496\nContent-Disposition: form-data; name=\"password\"\n\n12345678\n-----------------------------2285823208496\nContent-Disposition: form-data; name=\"phone_number\"\n\n080-2222-3333\n-----------------------------2285823208496--\n<\/pre>\n<p>Form data has a boundary to distinguish between which fields have which values.<br \/>\nSo the first step is to parse that out. The first line break in the string marks<br \/>\nthe string that represents the boundary, and then separate the form into their<br \/>\nkey value pairs.<\/p>\n<p>Following that is the Content-Disposition which gives prudent information for<br \/>\nthe type of data contained in the field. In this case it&#8217;s simply &#8220;form-data&#8221;,<br \/>\nbut other options include attachments, or files, which we will attempt to<br \/>\nparse in the next chapter. But for the moment, we will simply assume key value<br \/>\npairs and ignore this information.<\/p>\n<p>The name is the name field from the original form. Nothing special here, but the<br \/>\nuse of double quotations in this line allows us to use a regular expression to<br \/>\nextract this name from the given string.<\/p>\n<p>Following that is two line breaks before the actual values being sent to the server<br \/>\nare included. Since these are the values we sent to the server, they should be<br \/>\neasily recognizable, or at the very least easily debug-able by entering different<br \/>\nvalues to determine their position in the form.<\/p>\n<p>A sample implementation for parsing a basic form into a JSON object is as given<br \/>\nbelow.<\/p>\n<pre>function api_form( req, res ) {\n\n    var str = \"\";\n\n    req.on(\"data\", function(data) {\n\n        str += data;\n\n    });\n\n    req.on(\"end\", function() {\n\n        for(let i = 0; i &lt; str.length; i++) {\n\n            if(str[i] !== '\\n'){\n                continue;\n            }\n\n            let boundary = str.substr(0, i - 1);\n            str = str.split(boundary);\n            str.shift();\n            str.pop();\n\n            break;\n\n        }\n\n        let args = {};\n\n        for(let i = 0; i &lt; str.length; i++) {\n\n            let field = str[i].split(\"\\r\\n\");\n            let key = field[1].match( \/\"(.*?)\"\/ )[1];\n            args[key] = field[3];\n\n        }\n\n        str = JSON.stringify(args, null, 4);\n\n        res.writeHead(200, { \"Content-Type\" : \"text\/plain\" });\n        res.end( str );\n\n    });\n\n}\n<\/pre>\n<p>The result of the function is as included below.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/blog.wsd.sh\/wp-content\/uploads\/2020\/06\/fig_11.jpg\" alt=\"\" class=\"alignnone size-full wp-image-297\" width=\"1137\" height=\"882\" srcset=\"https:\/\/blog.wsd.sh\/wp-content\/uploads\/2020\/06\/fig_11.jpg 1137w, https:\/\/blog.wsd.sh\/wp-content\/uploads\/2020\/06\/fig_11-300x233.jpg 300w, https:\/\/blog.wsd.sh\/wp-content\/uploads\/2020\/06\/fig_11-1024x794.jpg 1024w, https:\/\/blog.wsd.sh\/wp-content\/uploads\/2020\/06\/fig_11-768x596.jpg 768w\" sizes=\"(max-width: 1137px) 100vw, 1137px\" \/><\/p>\n<p>In the next chapter we will continue to look at forms and attempt to parse a<br \/>\nfile out of form data.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this chapter we take the raw POST data that we uploaded in the previous chapter and parse it to JSON data so that we can handle it easier. In the next chapter we will change our focus to working with JSON data in a more direct fashion.<\/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\/296"}],"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=296"}],"version-history":[{"count":3,"href":"https:\/\/blog.wsd.sh\/index.php?rest_route=\/wp\/v2\/posts\/296\/revisions"}],"predecessor-version":[{"id":300,"href":"https:\/\/blog.wsd.sh\/index.php?rest_route=\/wp\/v2\/posts\/296\/revisions\/300"}],"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=296"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.wsd.sh\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=296"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.wsd.sh\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=296"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}