Return String

Basic Express 4

A few quick notes on Express 4 intended as a cheat sheet of common usecases.

Project Setup

Make sure you have Node and NPM installed. You can verify this by running node -v and npm -v in a terminal.

Create a new project with npm init, then run npm install express to install ExpressJS.

Finally we should create a file called server.js in our project folder for our code.

Basic HTTP Server

Our demo application accepts a GET requests at our root: / on port 8080. We can run the server with node server.js and connect to localhost:8080 with a browser. Our server should respond with hello world! which will be displayed in the browser.

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

// Environment variables
const PORT = 8080;

// Set up Express application
const app = express();
app.get('/', getHandler);

// Create HTTP server
http.createServer(app).listen(PORT, () => {
    console.log(`listening on ${PORT}...`);
});

// Sends Response with hello world!
function getHandler(req, res) {
    res.status(200).type('text/plain').send('hello world!');
}

POST and Body Parser

To parse the body of a request, we will need to use the body-parser package that is included with NodeJS. In this case we will accept JSON bodies from POST requests.

const express = require('express');
const bodyParser = require('body-parser');
const http = require('http');

// Environment variables
const PORT = 8080;

// Set up Express application
const app = express();
app.use(bodyParser.json());
app.post('/', postHandler);

// Create HTTP server
http.createServer(app).listen(PORT, () => {
    console.log(`listening on ${PORT}...`);
});

// Sends 202 Response and logs body
function postHandler(req, res) {
    console.log(JSON.stringify(req.body));
    res.status(202).end();
}

Serving Static Files

We can use express.static to load a directory of files we want to serve.

app.use(express.static('static-files')) will serve everything in the static-files folder at the root of our IP or domain: localhost:8080/FILE_NAME

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

// Environment variables
const PORT = 8080;

// Set up Express application
const app = express();

app.use(express.static('static-files'));

// Create HTTP server
http.createServer(app).listen(PORT, () => {
    console.log(`listening on ${PORT}...`);
});

If we wish to load our static files with a path prefix, we can add it to app.use like so: app.use('/public', express.static('static-files')) this will load the files at localhost:8080/public/FILE_NAME.

Coming Soon(ish):

More common tasks and a separate article on HTTPS.

Feel free to reach out on contact@returnstring.com with ideas.