Step 11

Update the server.js file as follows:

const path = require("path");
const express = require("express");
const app = express();
const port = process.env.PORT || 7000;

app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, "index.html"));
});

app.listen(port, () => {
  console.log(`Express app listening at http://localhost:${port}`);
});

Save the file and run it:

node server.js

Open the browser and visit http://localhost:7000/. You should see the BMI calculator app.

Let's explore the code:

  • The require("express") returns a function which we capture in the express variable.
  • This function returns an object which we capture in the app variable by invoking express().
  • The app object has methods for handling HTTP requests among other things.
  • The app.get() handles a HTTP Get request.
  • The first argument is a "path," a string representing part of a URL that follows the domain name. (See "Anatomy of a URL" for more information.)
  • The second argument is a callback function. The req and res bindings are objects representing the incoming and outgoing data.
  • The sendFile transfers a file at the given path. It also sets the Content-Type response HTTP header field based on the filename’s extension.
  • The path provided to sendFile must be an absolute path to the file. That's why I have used the Node's path module to get the absolute path to the index.html file.
  • The __dirname is a global variable built to Node that returns the path of the folder where the current JavaScript file resides.
  • The app.listen() binds and listens for connections on the specified port. This method is identical to Node's http.Server.listen(). It optionally takes a second argument, a callback function, which I've used to simply print a message to the terminal.

The application we've built here with Express is identical to the one we had built earlier with Node's HTTP Module. In fact, Express is built on top of Node's HTTP module but it adds a ton of additional functionality to it. Express provides a clean interface to build HTTP server applications. It provides many utilities, takes care of nuances under the hood, and allows for many other packages to be added as middleware to further the functionality of Express and your server application.

Save changes, commit and push your code. Then, make sure the Heroku App is working as expected!