To Tutorials and Projects
IT 231 -- Tutorial 4 -- Alternate Version
Goal: Create a test website and an Express server
to display the website pages on localhost.
Details
Your site will display pages for these sample routes:
/ /contact_us /specials /eiffel_tower
It will also display a route not found page if a route is entered other than these
four.
The HTML pages that correspond to these sample routes are
index.html,
contact-us.html,
specials.html,
eiffel-tower.png, and
route-not-found.html.
Follow these steps to complete the tutorial:
- Create a Node project named tutorial4-alt-<your last name>.
- Install Express in your project:
> npm i express
- Write a main.js script by completing the following
items:
- Require the express module; assign it to the constant named express.
- Require the path module; assign it to the constant named path.
- Define an app object, which will be the Express
server:
const app = express( );
- Add the nodemon module to your project.
- Set up a GET route for the homepage that displays the HTML file
index.html:
app.get("/", (req, res) => {
res.sendFile(path.join(
__dirname + '/index.html'));
});
If you prefer to put the HTML files in the views folder,
set up the route like this:
app.get("/", (req, res) => {
res.sendFile(path.join(
__dirname + '/views/index.html'));
});
- Also set up routes for /contact_us,
/specials, and /eiffel_tower.
- If any other route is entered, display route-not-found.html:
app.get("*", (req, res) => {
res.sendFile(path.join(
__dirname + '/file-not-found.html'));
});
- Set the server to listen on port 3000:
const PORT = 3000;
app.listen(PORT, ( ) => {
console.log("Server started; " +
`listening on port ${PORT}.`);
});
Notice that, in addition to the port argument,
the Express app object also accepts a callback function
that is called when the app starts listening.
Finish Tutorial 4 by implementing an external stylesheet for all HTML pages, and
including at least one image on one or more HTML pages.
- Set up a public folder for static access:
app.use(express.static('public'));
- Implement a set of hyperlinks on each page that link to the other pages in the
website. For example, on the index page, you could use these hyperlinks:
<p>
<a href="/contact_us">Contact Us</a>
<a href="/specials">Specials</a>
<a href="/eiffel_tower">Eiffel Tower</a></p>
</p>
- Create the external stylesheet styles.css and place it
in a folder named public within the project folder.
Remove all the <style> elements from the HTML pages.
- Modify the html files to all use the styles.css stylesheet:
<head>
<title>Contact Us</title>
<link rel="stylesheet" href="styles.css">
</head>
- Place the image eiffel-tower.png in the
public folder.
- Create an HTML file named eiffel-tower.html that displays the Eiffel Tower image.
Your stylesheet should include a width property to
display the image at an appropriate size. If you include both
width and height properties, you risk distorting
the aspect ratio if the image.