Exercise - Create a new Express web application

Completed

Tailwind Traders has tasked you with creating a simple API using the Express framework. The online retailer wants to evaluate Express to see if it's easy to work with. As part of that evaluation, they want you to build a web application that serves different routes.

Open project in development container

Use the provided development container to complete the exercises in this module. The development container is preconfigured with the tools you need to complete the exercises.

  1. Start the process to create a new GitHub Codespace on the main branch of the MicrosoftDocs/node-essentials GitHub repository.

  2. On the Create codespace page, review the codespace configuration settings and then select Create new codespace

    Screenshot of the confirmation screen before creating a new codespace.

  3. Wait for the codespace to start. This startup process can take a few minutes.

  4. Open a new terminal in the codespace.

    Tip

    You can use the main menu to navigate to the Terminal menu option and then select the New Terminal option.

    Screenshot of the codespaces menu option to open a new terminal.

  5. Validate that Node.js is installed in your environment:

    node --version
    

    The dev container uses a Node.js LTS version such as v20.5.1. The exact version might be different.

  6. The remaining exercises in this project take place in the context of this development container.

Create a basic web app with Express

Create a basic application that handles requests.

  1. Open a terminal in the dev container.

  2. Use the following commands to create a new Node.js project and install the Express framework:

    mkdir my-express-app
    cd my-express-app
    npm init -y
    npm install express
    

    The init command creates a default package.json file for your Node.js project. The install command installs the Express framework.

  3. In a code editor, open the package.json file.

    In the dependencies section, locate the express entry:

    "dependencies": {
      "express": "^4.18.2"
      ...
    }   
    

    This entry indicates the Express framework is installed. Your version may be more recent. This sample code uses version 4 of the Express framework.

  4. In a code editor in the my-express-app folder, create a file named app.js, and add the following code:

    const express = require('express');
    const app = express();
    const port = 3000;
    
    app.get('/', (req, res) => res.send('Hello World!'));
    
    app.listen(port, () => console.log(`Example app listening on port ${port}! http://localhost:${port}/`));
    

    The code creates an instance of an Express application by invoking the express() method. This is the top-level function exported by the Express module. All further configuration and functionality is added via the app variable.

    Notice how the code sets up a route to slash /, the root, with the syntax:

    app.get('/', (req, res) => res.send('Hello World!'));

    After setting up the route, the code starts the web application by invoking the listen() method:

    app.listen(port, () => console.log('Example app listening on port ${port}!'));

  5. Open a terminal for this subfolder by right-clicking the subfolder name and selecting Open in integrated terminal.

  6. In the terminal, run the following command to start the Express web application:

    node app.js
    

    You should see the following output:

    Example app listening at http://localhost:3000
    

    This output means your app is up and running and ready to receive requests.

  7. You can right-click and select the URL in the terminal or you can open the browser when Visual Studio Code pops up a notification asking if you want to Open in browser. You should see the following output:

    Hello World!
    
  8. In the terminal, press Ctrl + C to stop the web Express program.

Create a web app that returns JSON data

Use the same app.js file to add a new route.

  1. In a code editor, open the app.js file.

  2. Add the following code after the existing app.get syntax after the code for the first route, /:

     app.get('/products', (req, res) => {
         const products = [
             { id: 1, name: 'hammer' },
             { id: 2, name: 'screwdriver' },
             { id: 3, name: 'wrench' },
         ];
    
         res.json(products);
     });
    
  3. Make sure your app.js file looks like this example:

     const express = require('express');
     const app = express();
     const port = 3000;
    
     app.get('/', (req, res) => res.send('Hello World!'));
    
     app.get('/products', (req, res) => {
         const products = [
             { id: 1, name: 'hammer' },
             { id: 2, name: 'screwdriver' },
             { id: 3, name: 'wrench' },
         ];
    
         res.json(products);
     });
    
     app.listen(port, () => {
         console.log(`Example app listening on port ${port}! http://localhost:${port}/`);
     });
    
  4. Save your changes to the app.js file and close the file.

  5. In the terminal, run the following command to restart the web Express app:

    node app.js
    

    You should see the following output:

    Example app listening at http://localhost:3000
    
  6. In a browser, return to the tab from the previous step and add the new route, /products, to the end of the URL. You should see the following JSON output:

    [{"id":1,"name":"hammer"},{"id":2,"name":"screwdriver"},{"id":3,"name":"wrench"}]
    
  7. In the terminal, press Ctrl + C to stop the web Express program.

Congratulations! You implemented a second route that can serve up static JSON data.