Quick Index
Goal


Our goal is to code a simple web server in Express.

Example Steps


Create Project Directory
Create a project directory named "express-1a"
/express-1a
Initialize Project
>npm init
Install Packages
Use the npm install command to install the public packages http-status-codes and express

Note we install two packages here (we could also do this by running two commands).
>npm install http-status-codes express
Code
Create file main.js with source shown.

We're using some new protocol like: type, status, response send, and express get.

Gotcha 🐞 be familiar with response send to avoid a gotcha.

Recall that both "started" and "homeFct" are callback functions.
"use strict";

const
	port = 3000,
	express = require("express"),
	codes = require('http-status-codes'),
	app = express(),
	msg = `Server started on port: ${port}`;
	
//simple function to log a startup note
const started = () => console.log(msg);

const homeFct = (req, res) => {
	res.type('html');
	res.status(codes.OK);
	res.send('Greetings from the web server');
};

//route home path "/" to "homeFct"
app.get("/", homeFct);

//start the web server app
app.listen(port, started);
Run
Start the web server

Note: you very likely can setup a shortcut in your IDE to run the current file
>node main
Open Browser on URL
  • Open a web browser.
  • Go to the address bar
  • Enter "http://localhost:3000/" in the address bar
  • Or, you can click directly on the url shown here to the right


http://localhost:3000/

Greetings from the web server


Next


Next example...











Navigation