Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

358 CHAPTER 8 Websites and services


This statement starts with app.use, which mounts a path from which to serve files. In the
app.use function, express.static specifies the location of static files. In this case, you need to
create a public folder within your application.
After creating the public folder, create an HTML file in the public folder called HelloForm.
html containing the following.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<form method="get" action="/SubmitHello">
Enter Name: <input type="text" name="userName" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

This HTML file contains a <form> element, and its method attribute is set to GET, whereas
the action attribute is set to /SubmitHello. This means that you need a resource called /
SubmitHello at the server that can handle the data passed to the server in the QueryString.
In the app.js file, add the following code after the app.use statement.
app.get('/SubmitHello', function (request, response) {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.write('Hello ' + request.query.userName + '!<br />');
response.end('Have a great day!');
console.log('Handled request from ' + request.query.userName);
});

This code is similar to the original app.get statement except that the SubmitHello resource
is specified, and the QueryString is accessible by using request.query. The following is the
completed app.js file.
var express = require('express');
var app = express();

app.use(express.static(__dirname + '/public'));

app.get('/SubmitHello', function (request, response) {
response.writeHead(200, { 'Content-Type': 'text/html' });
response.write('Hello ' + request.query.userName + '!<br />');
response.end('Have a great day!');
console.log('Handled request from ' + request.query.userName);
});

var port = 8080;
app.listen(port);
console.log('Listening on port: ' + port);
Free download pdf