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
- Create a new Node.js Repl project
- Name it "Express App"
- Create a new file named app.js in the current directory
- For test purposes, add a
console.log('hello')statement to app.js - Create another new file, this one named .replit
- In the .replit file, add
run = "node app.js" - 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.
- Import the
expressmodule usingrequire, and store it in aconstvariable namedexpress - Create
constvariables forhostnameandport- These should be
'0.0.0.0'and8080respectively
- These should be
- Initialize an Express app by calling the
expressmodule as a function, and store it in a variable namedapp - Define a new function named
handleHomeRequestthat hasrequestandresponseas parameters - In the body of the
handleHomeRequestfunction, useresponse.sendto display 'Hello World!' to the user - Use
app.getto specify that when a browser goes to the root of the server ('/'),handleHomeRequestshould runapp.get('/', handleHomeRequest); - Define a new function named
listenCallbackthat logs a message to the console saying the server is running - Finally, use
app.listento listen on the appropriate port on the host, and calllistenCallbackwhen listening - 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!
- Define a new function named
handleInfoRequestthat hasrequestandresponseas parameters - In the body of the
handleInfoRequestfunction, useresponse.sendto show an HTML header to the user that says "Info" - Use
app.getto specify that when a browser goes to the'/info'endpoint,handleInfoRequestshould run - Test out the new endpoint by clicking the "Run" button, opening the page in a new tab, and appending
/infoto 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.
- Find the
handleHomeRequestfunction - Update the
response.sendto send an<a>element instead of 'Hello World!' - Make the
hreffor the<a>point to the info page:href="/info" - 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!
- Create a new file in the project directory named info.html
- Fill out some basic HTML in the file
- Include an
<a>link back to the home page:href="/"
- Include an
- At the top of the app.js file, import the
pathmodule and store it in a variableconst path = require('path'); - In the
handleInfoRequestfunction, remove theresponse.sendstatement - Create a new variable named
infoPath, and usepath.jointo combine__dirnameand'info.html'to get the absolute path of the HTML filelet infoPath = path.join(__dirname, 'info.html'); - Use
response.sendFileto pass HTML file to the response - Load up the server and check out the
/infoendpoint 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);