Shoulder.dev Logo Shoulder.dev

Setting Up Basic Express Functionality in benhall/express-demo

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
  1. Familiarize yourself with the project structure.

  2. Open the app.js file in your text editor.

  3. Ensure that Express is imported and an instance is stored in the app variable:

const express = require('express');
const app = express();
  1. Define a PORT variable and specify the address:
const PORT = process.env.PORT || 3000;
  1. Import Express.json() middleware:
app.use(express.json());
  1. 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');
});
  1. Start the Express server by listening on the defined PORT:
app.listen(PORT, () => {
console.log(`Express server currently running on port ${PORT}`);
});
  1. 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:

  1. Verify that the Express server is running by checking the console output for the “Express server currently running on port …” message.
  2. Open your browser and navigate to http://localhost:3000. Verify that the “Hello World” message is displayed.
  3. Change the message in the routes/index.js file and save the changes. Refresh the browser to verify that the updated message is displayed.