Express Web Server: Individual Exercises
Complete the following exercises to update the Express project and personalize it.
A New Page
First, create yet another possible route for the website. This one should display a message of "This is a new page!" when the user appends /new to the URL. This will be very similar to how the existing pages are set up, so use those as a reference.
- Find the definition for the
handleHomeRequestfunction in the app.js file - Under that, define a new function named
handleNewRequest - Give the function two parameters:
requestandresponse - In the body of the
handleNewRequestfunction, callresponse.send - Pass in
'This is a new page!'to theresponse.sendcall - Under the function definitions, find the
app.getcalls - Under those, add a new
app.getcall- For the first argument, pass in
'/new'(route for URL) - For the second argument, pass in
handleNewRequest(function name)
- For the first argument, pass in
- Run the server, open the site in a new tab, and append
/newto the URL - Verify that the message for the new page appears!
function handleNewRequest(request, response) {
response.send('This is a new page!');
}
app.get('/new', handleNewRequest);
A New "Home"
Using simple text responses can be helpful for testing, but for a real website, HTML can do a lot more. Update the homepage so that instead of simply sending text, it sends a whole HTML document.
- Create a new HTML file named home.html in the project directory
- In the home.html file, add some HTML to create a custom page welcoming the user
- It should have a header that says "Home"
- It should have links to the Info page and New page
- It can also have pictures and introductory information
- Feel free to add anything at all!
- In the body of the
handleHomeRequestfunction, replace the existing code with a new variable namedhomePath - Set the
homePathvariable to be a call topath.join, passing in__dirnameand the filename- HINT: This is similar to the
handleInfoRequestfunction
- HINT: This is similar to the
- Under that, use
response.sendFileto send thehomePathfile - Run the server and test it out to make sure the homepage HTML appears!
function handleHomeRequest(request, response) {
let homePath = path.join(__dirname, 'home.html'); // assuming a 'home.html' file exists
response.sendFile(homePath);
}
Yet Another Page
Add another endpoint with another HTML page for the site! This will be similar to how the Home and Info pages work. This new page should be all about your favorite food.
Creating the HTML
- Create a new HTML file named food.html in the project directory
- In the food.html file, add some HTML to create a page
- It should have a header with your favorite food
- It should have a picture of your favorite food
- It should have a link to the Home page
- It can have anything else you want on it too
Creating the Handler Function
- Open the app.js file for editing
- Under the
handleInfoRequestfunction, define a new function- Name it
handleFoodRequest - Give it two parameters:
requestandresponse
- Name it
- In the body of the function, create a new variable named
foodPath - Set the
foodPathvariable topath.join, passing in__dirnameand the filename - Under that, use
response.sendFileto send thefoodPathfile
Hooking Up the Route
- Find the
app.getfunction calls in the app.js file - Under those, make another
app.getcall - Pass in
/foodfor the route, andhandleFoodRequestfor the function
Adding a Link from Home
- Open the home.html file for editing
- Somewhere in the file, add an
<a href="/food">to link to the Food page
Run the server and verify that it is now possible to go to the Food page!
An Info Form
In the info.html file, there should be an HTML form that will allow the user to enter information to be received by the server.
- At the bottom of the
bodyof the info file, add a<form></form>element- Set the
actionattribute of the form to point back to the current place:'/info'
- Set the
- Within the form, add a
<p></p>that says "What type of information would you like?" - Under the
p, add a text<input />- Set the
nameattribute of the input to'infoType'
- Set the
- Under the
input, add another<input />with typesubmitand valueSubmit
<form action="/info">
<p>What type of information would you like?</p>
<input type="text" name="infoType" />
<input type="submit" value="Submit" />
</form>
Receiving the Form Request
In the app.js file, in the handleInfoRequest function, there should be code to properly handle GET requests from the new form. The form information will be sent as query parameters.
- At the top of the app.js file, import the
urlmodule, and store it in aconstnamedurlconst url = require('url'); - In the body of the
handleInfoRequestfunction, find theinfoPathvariable declaration - Under that, declare a new variable named
parsedUrl - Set the
parsedUrlvariable to the result of a call tourl.parse- Pass in
request.urlfor the first argument - Pass in
truefor the second argument
- Pass in
- Under that, create a new variable named
queryParams - Set the
queryParamsvariable toparsedUrl.query - Under that, use
console.logto display thequeryParamsvariable - Load up the server, navigate to the
/infopage, and submit the form to see thequeryobject in the console!
function handleInfoRequest(request, response) {
let infoPath = path.join(__dirname, 'info.html');
let parsedUrl = url.parse(request.url, true);
let queryParams = parsedUrl.query;
console.log(queryParams);
response.sendFile(infoPath);
}
Dynamic Pages - Penguins
Note: This part will be fairly challenging.
Now that the server is receiving the form data, it's possible to respond dynamically!
Creating the Penguin Page HTML
Start by creating a new HTML document containing information about penguins.
- Create a new HTML file named penguinInfo.html in the project directory
- Fill out the penguinInfo.html file with some information about penguins
- For example, a group of penguins in the water is called a raft but on land they’re called a waddle!
- At the bottom of the HTML body, copy and paste the entire
formelement from info.html- Copying and pasting like this is not ideal, but it works for now
Showing the Penguin Page
- Switch back to the app.js file, and find the
handleInfoRequestfunction - Under the
parsedUrlvariable declaration, create a variable namedinfoType - Set the
infoTypevariable toqueryParams.infoType- This should hold whatever the user entered in the form
- Create an
ifstatement to check whether theinfoTypequery parameter was "penguin" - If the user did enter "penguin", set the
infoPathto point to the new penguinInfo.html file - Load up the server and enter "penguin" on the
/infopage to see the content change dynamically!
function handleInfoRequest(request, response) {
let infoPath = path.join(__dirname, 'info.html');
let parsedUrl = url.parse(request.url, true);
let queryParams = parsedUrl.query;
let infoType = queryParams.infoType;
if (infoType == 'penguin') {
infoPath = path.join(__dirname, 'penguinInfo.html');
}
console.log(queryParams);
response.sendFile(infoPath);
}
Another Dynamic Page - Giraffes
Next, create another dynamic info page - this one should be about giraffes.
Creating the Giraffe Page HTML
Start by creating a new HTML document containing information about giraffes.
- Create a new HTML file named giraffeInfo.html in the project directory
- Fill out the giraffeInfo.html file with some information about giraffes
- For example, giraffes are the tallest mammals on earth
- At the bottom of the HTML body, copy and paste the entire
formelement from info.html- Copying and pasting like this is not ideal, but it works for now
Showing the Giraffe Page
- Switch back to the app.js file, and find the
handleInfoRequestfunction - Under the
if (infoType == penguin)check, add anelse if - For the
else ifcondition, check if the query parameter was "giraffe" - If the user did enter "giraffe", set the
infoPathto point to the new giraffeInfo.html file - Load up the server and enter "giraffe" on the
/infopage to see the content change dynamically!
More Info Pages
Create additional HTML pages, and make the handleInfoRequest function properly route to them based on input from the user! This could be information about any topic. Try to add as many info pages as possible.