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
express
module usingrequire
, and store it in aconst
variable namedexpress
- Create
const
variables forhostname
andport
- These should be
'0.0.0.0'
and8080
respectively
- These should be
- Initialize an Express app by calling the
express
module as a function, and store it in a variable namedapp
- Define a new function named
handleHomeRequest
that hasrequest
andresponse
as parameters - In the body of the
handleHomeRequest
function, useresponse.send
to display 'Hello World!' to the user - Use
app.get
to specify that when a browser goes to the root of the server ('/'
),handleHomeRequest
should runapp.get('/', handleHomeRequest);
- Define a new function named
listenCallback
that logs a message to the console saying the server is running - Finally, use
app.listen
to listen on the appropriate port on the host, and calllistenCallback
when 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
handleInfoRequest
that hasrequest
andresponse
as parameters - In the body of the
handleInfoRequest
function, useresponse.send
to show an HTML header to the user that says "Info" - Use
app.get
to specify that when a browser goes to the'/info'
endpoint,handleInfoRequest
should run - 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.
- Find the
handleHomeRequest
function - Update the
response.send
to send an<a>
element instead of 'Hello World!' - Make the
href
for 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
path
module and store it in a variableconst path = require('path');
- In the
handleInfoRequest
function, remove theresponse.send
statement - Create a new variable named
infoPath
, and usepath.join
to combine__dirname
and'info.html'
to get the absolute path of the HTML filelet infoPath = path.join(__dirname, 'info.html');
- Use
response.sendFile
to pass HTML file to the response - 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);