Express
ExpressJS (or simply Express) is a web framework for Node. It facilitates building web servers and APIs.
Open the terminal and install Express.
yarn add express
Notice three changes as a result of installing Express:
- Express is added as a dependency to
package.json
. - The
node_modules
folder is added to the root directory. Make sure to exclude this folder from your Git repository. - A
yarn.lock
is added to the root of your project.
You are familiar with all this, as you have seen them in previous chapters.
Here is a minimal Express application:
import express from "express";
const port = 3000;
const app = express();
app.get("/", (req, res) => {
res.send("Hello Express");
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
Go to the terminal and run yarn start
. You will see the following message printed in the terminal:
Server running at http://localhost:3000/
While the Express app is running, open your browser and go to http://localhost:3000/. You will see the "Hello Express" message!
Recall: to stop the app, you must halt the process by pressing Ctrl
+ C
.
The application we've built here with Express is identical to the one we had made earlier with Node's HTTP Module. 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 offers 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.