Setting up an Express server in Node

Before we begin

You will need to have node and npm (node package manager) installed on your machine.

If you are unsure about this, check out the npm blog post on the subject,
How to Install Npm, but npm should be installed with node itself.

Because we are using npm to keep track of our dependencies we will need to initialize npm in our project directory.

1
2
3
mkdir yourProject
cd yourProject
npm init

You will then be walked through creating the package.json file for your project. It will auto populate the name as your directory and ask you for some other settings. Just hitting enter until the end will populate package.json with default values. You can edit these later just by opening the file.

Creating the server

app.js

A standard method to create your express server is to put it in a file called app.js.

1
touch app.js

Requiring Express

Like all of our dependencies, we will have to install express in our node project and “require” express in app.js. Requiring a file in your file gives you access to that file’s module.exports.
In terminal:

1
npm install express --save

In app.js

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

Notice that since express is an included npm package, we will not need to give it a path. Npm will automatically look in node_modules in the current folder and up the directory chain.
We have assigned the returned value of express() to app and this is what we will use to interact with the node server.

Starting the server

app.listen can be used to start the HTTP server and listen on the specified port.

1
2
3
app.listen('3333', function(){
console.log('Listening on port 3333');
})

To start the server you would run

1
node app.js

in the terminal.
In this case port 3333 is on our local host so we can access it at http://localhost:3333. If we navigated there currently, there would be no response from the server, since we haven’t set up any routes.

Adding a route

Express adheres to the restful api and makes it easy to receive and respond to HTTP GET, PUT, POST, and DELETE verbs. An exampe of a simple get request would be in app.js:

1
2
3
app.get('/', function (req, res){
res.send('You\'ve reached the home directory');
});

If you send a get request to http://localhost:3333, such as by opening it in a broswer it will send the response “You’ve reached the home directory!”