Scenario:
You aim to create a simple Express application using benhall/express-demo as a foundation. This example will walk you through initializing the Express app, defining routes, and handling requests using the provided starter code.
Solution:
First, let’s familiarize ourselves with the project structure:
benhall/express-demo/
├── bin/
│ └── www
├── public/
│ ├── stylesheets/
│ │ └── style.css
├── routes/
│ ├── index.js
│ └── users.js
├── views/
│ ├── error.hbs
│ ├── index.hbs
│ └── layout.hbs
├── Dockerfile
├── app.js
├── docker-compose.yml
├── nodemon.json
└── package.json
Familiarize yourself with the project structure.
Open the
app.js
file in your text editor.Ensure that Express is imported and an instance is stored in the
app
variable:
const express = require('express');
const app = express();
- Define a PORT variable and specify the address:
const PORT = process.env.PORT || 3000;
- Import Express.json() middleware:
app.use(express.json());
- Define routes and HTTP request methods in the
routes
directory. For this example, we will create a simple route for the root path (“/”) that returns a “Hello World” message.
Open the routes/index.js
file and add the following code:
app.get('/', (req, res) => {
res.send('Hello World');
});
- Start the Express server by listening on the defined PORT:
app.listen(PORT, () => {
console.log(`Express server currently running on port ${PORT}`);
});
- Save the changes and run the project by executing the following command in your terminal:
npm start
Your project is now running on http://localhost:3000
. Navigate to your browser, and you should see the “Hello World” message.
Tests:
- Verify that the Express server is running by checking the console output for the “Express server currently running on port …” message.
- Open your browser and navigate to
http://localhost:3000
. Verify that the “Hello World” message is displayed. - Change the message in the
routes/index.js
file and save the changes. Refresh the browser to verify that the updated message is displayed.