360 CHAPTER 8 Websites and services
Did you notice that the URL to get the HelloForm.html page was the following?
http://localhost:8080/HelloForm.html
You didn’t need to provide the word “public” in the URL because the app.use function
didn’t specify a resource folder for the URL. The app.use specified the location of the files
only, so the URL path is the root of the website (\). You can specify the URL path explicitly by
inserting the path in front of the original argument, as shown in the following example.
app.use('/forms', express.static(__dirname + '/public'));
After making this change, run the application again. This time, enter the following URL in
the browser.
http://localhost:8080/Forms/HelloForm.html
If you try the original URL, you might still see the form because it’s cached. If so, refresh
your browser screen, and you no longer can retrieve the HelloForm.html from the original
URL.
Parsing posted form data
The previous examples demonstrated the ability to use Node.js to serve a webpage and pro-
cess the QueryString data by using the GET method, but in the previous chapter, you learned
that in addition to being able to attach data to the URL through the QueryString, you can put
data in the message body by using the POST method.
In this section, you learn to process the postback data by using a formidable package. This
package provides helper methods that simplify posted data retrieval.
Copy the HelloForm.html file to a new file called HelloPost.html in the same public folder.
Modify the HTML in the HelloPost.html by changing the <form> element’s method attribute
to post and changing the action attribute to SubmitHelloPost. The completed HelloPost.html
file should look like the following.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<form method=”post” action=”/SubmitHelloPost”>
Enter Name: <input type="text" name="userName" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Because the method attribute is set to POST, the processing of the data is different, which
is why a new action is provided. In the meantime, the existing HTML page continues to
operate.