Express Web Server: Code-Along

Follow the steps below to create an npm project that uses Express to run a simple web server.

Getting Started

  1. Create a new Node.js Repl project
  2. Name it "Express App"
  3. Create a new file named app.js in the current directory
  4. For test purposes, add a console.log('hello') statement to app.js
  5. Create another new file, this one named .replit
  6. In the .replit file, add run = "node app.js"
  7. Click the "Run" button to run the program, and make sure it works so far

Creating a Simple Express Web App

At first, creating an Express web server is a lot like creating a web server with the http module. However, the capabilities of the Express framework make it much easier to go beyond the basics. Start building the server in the app.js file by following the steps below.

  1. Import the express module using require, and store it in a const variable named express
  2. Create const variables for hostname and port
    • These should be '0.0.0.0' and 8080 respectively
  3. Initialize an Express app by calling the express module as a function, and store it in a variable named app
  4. Define a new function named handleHomeRequest that has request and response as parameters
  5. In the body of the handleHomeRequest function, use response.send to display 'Hello World!' to the user
  6. Use app.get to specify that when a browser goes to the root of the server ('/'), handleHomeRequest should run
     app.get('/', handleHomeRequest);
    
  7. Define a new function named listenCallback that logs a message to the console saying the server is running
  8. Finally, use app.listen to listen on the appropriate port on the host, and call listenCallback when listening
  9. Test out the server by clicking the "Run" button

Notice that after clicking "Run", the package.json file should automatically be updated to include express as a dependency. It should also automatically run the npm install command, which will install the express module on the server. This is all thanks to Repl.it; without it, a developer would have to do all of this manually!

Code

const express = require('express');

const hostname = '0.0.0.0';
const port = 8080;

let app = express();

function handleHomeRequest(request, response) {
    response.send('Hello World!');
}

app.get('/', handleHomeRequest);

function listenCallback() {
    console.log('Server running');
}

app.listen(port, hostname, listenCallback);

Adding Multiple Endpoints

It is much simpler to add additional HTTP endpoints using the Express framework!

  1. Define a new function named handleInfoRequest that has request and response as parameters
  2. In the body of the handleInfoRequest function, use response.send to show an HTML header to the user that says "Info"
  3. Use app.get to specify that when a browser goes to the '/info' endpoint, handleInfoRequest should run
  4. Test out the new endpoint by clicking the "Run" button, opening the page in a new tab, and appending /info to the URL

Code

function handleInfoRequest(request, response) {
    response.send('<h1>Info</h1>');
}

app.get('/info', handleInfoRequest);

Linking to the New Page

There should be a link to the new endpoint from the homepage.

  1. Find the handleHomeRequest function
  2. Update the response.send to send an <a> element instead of 'Hello World!'
  3. Make the href for the <a> point to the info page: href="/info"
  4. Run the program, and verify that it is possible to click the link on the homepage and go to the info page!
function handleHomeRequest(request, response) {
    response.send('<a href="/info">Info page</a>');
}

Sending HTML Files

So far the webpages are not very exciting, but it would be very annoying put a lot of HTML into a template string. Instead, Express makes it possible to send a whole HTML file as a response!

  1. Create a new file in the project directory named info.html
  2. Fill out some basic HTML in the file
    • Include an <a> link back to the home page: href="/"
  3. At the top of the app.js file, import the path module and store it in a variable
     const path = require('path');
    
  4. In the handleInfoRequest function, remove the response.send statement
  5. Create a new variable named infoPath, and use path.join to combine __dirname and 'info.html' to get the absolute path of the HTML file
     let infoPath = path.join(__dirname, 'info.html');
    
  6. Use response.sendFile to pass HTML file to the response
  7. Load up the server and check out the /info endpoint to make sure the info.html file renders properly!

Final Code

const express = require('express');
const path = require('path');

const hostname = '0.0.0.0';
const port = 8080;

let app = express();

function handleHomeRequest(request, response) {
    response.send('<a href="/info">Info page</a>');
}

function handleInfoRequest(request, response) {
    let infoPath = path.join(__dirname, 'info.html');
    response.sendFile(infoPath);
}

app.get('/', handleHomeRequest);
app.get('/info', handleInfoRequest);

function listenCallback() {
    console.log('Server Running');
}

app.listen(port, hostname, listenCallback);

results matching ""

    No results matching ""