Minimal Express Server


This article goes over how to set up a minimal Express web server.

Prerequisites

Server

Install express:

$ npm install express

Create index.js:

$ touch index.js

Require the module:

const express = require('express');

Then initialize the app:

const app = express();

Create the index route:

app.get('/', (req, res, next) => {
  res.send('<h1>Hello, Express!</h1>');
});

req and res are abbreviations of request and response, respectively.

Listen on port 3000:

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}`));

Run the server:

$ node index.js

Go to http://localhost:3000 to access the site.

Code

package.json:

{
  "dependencies": {
    "express": "latest"
  }
}

index.js:

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

app.get('/', (req, res, next) => {
  res.send('<h1>Hello, Express!</h1>');
});

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}`));

Demo

The Repl.it demo includes:

  • morgan (HTTP request logger)
  • route not found (404 error)
  • error handling (500 internal server error)


Please support this site and join our Discord!