Dissecting the code
Let's take a closer look at our Express app:
const express = require("express");
const app = express();
const port = 5000;
app.get("/", (req, res) => {
res.send("Hello Express!");
});
app.listen(port, () => {
console.log(`Express app listening at http://localhost:${port}`);
});
We will explore it line by line:
- The
require("express")
returns a function which we capture in theexpress
variable. - This function returns an object which we capture in the
app
variable by invokingexpress()
. - 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. We'll talk about it shortly.
- The
app.listen()
binds and listens for connections on the specified port. This method is identical to Node'shttp.Server.listen()
. It optionally takes a second argument, a callback function, which I've used to simply print a message to the terminal.