- Initialized
npm
project withpackage.json
file. See: Getting started withnpm
. express
installed as project dependency.- Entry page (i.e.
server.js
) present in the project root.
project-root
├── node_modules
├── package-lock.json
├── package.json
└── server.js
-
Load project dependencies:
const express = require('express');
-
Create an express server. The interface for every module is unique. Express wants you to start by invoking the function that
express
exports torequire()
.const app = express();
express()
returns an object. It includes many methods that come in handy; today's favourite isapp.get()
which allows us to attach middleware toGET
requests.
-
Add endpoint handler for
GET /
requests (i.e. the home page):app.get('/', (request, response) => { response.send('Hello World!') })
-
Set a port the server will listed to.
process.env.PORT
points to an optional.env
file (seedotenv
) that will default to3000
if it doesn't exist.const PORT = process.env.PORT || 3000;
-
Start the server.
app.listen(PORT, function(){ console.log(`Listening on port ${PORT}`); });
- The server will start inside the terminal window (making it pretty useless, besides logging to the console).
- [Express: Add an additional
GET
endpoint handler] - Express: Catch
404 Not Found
errors - Express: Serving static files