Skip to content

Instantly share code, notes, and snippets.

@acidtone
Last active May 22, 2023 03:55
Show Gist options
  • Save acidtone/8a188adf6e85a913f7f88c4f6cd53677 to your computer and use it in GitHub Desktop.
Save acidtone/8a188adf6e85a913f7f88c4f6cd53677 to your computer and use it in GitHub Desktop.
Express: Hello World!

Express: Hello World!

Prerequisites

  1. Initialized npm project with package.json file. See: Getting started with npm.
  2. express installed as project dependency.
  3. Entry page (i.e. server.js) present in the project root.

Example directory structure

project-root
    ├── node_modules
    ├── package-lock.json
    ├── package.json
    └── server.js

Instructions

  1. Load project dependencies:

    const express = require('express');
  2. Create an express server. The interface for every module is unique. Express wants you to start by invoking the function that express exports to require().

    const app = express();
    • express() returns an object. It includes many methods that come in handy; today's favourite is app.get() which allows us to attach middleware to GET requests.
  3. Add endpoint handler for GET / requests (i.e. the home page):

    app.get('/', (request, response) => {
      response.send('Hello World!')
    })
  4. Set a port the server will listed to. process.env.PORT points to an optional .env file (see dotenv) that will default to 3000 if it doesn't exist.

    const PORT = process.env.PORT || 3000;
  5. 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).

Related Gists

{
"name": "hello-express",
"version": "1.0.0",
"description": "An introductory express app",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Tony Grimes",
"license": "MIT",
"dependencies": {
"express": "^4.17.1"
}
}
const express = require('express');
const app = express();
app.get('/', (request, response) => {
response.send("Hello World!");
})
const PORT = process.env.PORT || 3000;
app.listen(PORT, function() {
console.log(`Example app listening at http://localhost:${PORT}`);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment