Intro to Express

Express is a "fast, unopinionated, minimalist web framework for Node.js." It is considered a very thin, lightweight framework that uses Node.js APIs to take common uses of Node.js and abstract (simplify) them for easier use by the developer. In this document, we will run through how to create a very basic web server that will run on a port and return a response to a basic HTTP GET request.

Installation

  • Create project folder/directory on your file system
  • From the cmd prompt run: npm init. If you want to skip all the questions, you can add the -y flag. (npm init -y).
    • This creates a package.json file that makes it easier to set up your project in the future. It's also where we'll save a list of dependencies that are required for this app to work. For example, since it's going to be an express app, we'll have express listed as a dependency.
  • From the cmd prompt, anytime you need a new NPM package run: npm install --save <packageName> (e.g.: npm install --save express)
    • Many times online you will be told to just run npm install <packageName>. Unless you have a good reason not to, you should always add the --save flag to this command so that you can automatically add the package you're installing as a dependency in package.json.

Very Basic Express Server Setup

  • Create a new JavaScript file called app.js in the project folder you created earlier. It should sit beside the package.json file that was called (instead of being inside some other directory).
  • We need to bring in the express module by using the Node.js require() function. Then we create an instance of express and save it to a variable called app.
// In app.js

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

The last thing we absolutely have to do for a server to technically be running is to tell our app to listen to a certain port.

// In app.js

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

app.listen(3000);

Now if you run node app.js in the terminal, you'll see the terminal seemingly freeze up with a blinking cursor. This is actually your server running! It's listening to http://localhost:3000 for some kind of request to come in. We haven't set it up to handle any requests quite yet, but now you know your server is running!

If you want to more clearly see that your server is running, the .listen() method can take an optional second callback parameter:

// In app.js

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

app.listen(3000, () => {
    console.log("App is listening on port 3000!");
});

You'll have to kill the server in the command line (control + C) and restart it so that your changes are reflected in the new running server. Okay, big deal right? We literally can't do a single thing with this yet...

Aside: Nodemon

Before we get too far in developing our server, there's a nice NPM package called Nodemon that will automatically watch for changes in the running JavaScript file and will restart automatically. This way you won't have to kill and restart your server all the time while you're developing it!

We'll install it globally, since it's a developer tool and not a tool your app will really be using itself. Installing it globally also means we can use it on any other JS file without having to install it again each time.

Anywhere in your terminal, type npm install -g nodemon. That's it! Now you can use the nodemon tool by typing nodemon <filename>.js in your terminal, and it will do all the work of restarting itself anytime it sees a change in the file.

Okay, let's move on.

Express Routes

Express makes it very easy for us to stick "routes" directly on our new app, organized by the HTTP request method we're expecting to receive at the given route. In other words, in order to tell my server to respond to a GET request at the base http://localhost:3000 address, all I have to do is add the following before my app.listen() code:

app.get('/', (req, res) => {
    res.send("Hello world!");
});

If you're using nodemon, your server should have restarted automatically once you save the file with the changes. If you're not using nodemon, quit out of your old server (control + C) and run it again (node app.js).

If you typed in everything correctly, you should now be able to open Postman, make a GET request to localhost:3000 and see, in very boring text, "Hello world!" returned as a response.

There are much better ways to organize your routes than to stick everything in your main server file (which you can learn about here), but for learning the basics of Express, this will work for now.

Aside: "req" and "res"

This is something you'll see very frequently in all server code, including Node.js and express. "req" is short for "request", "res" is short for "response". Here's the express request docs and the express response docs for in-depth study.

Note: This is how it is commonly represented, but you can put whatever names you want in here. You could say foo and bar if you wanted, but you'd have to remember that the first one (foo) represented the request and the second one (bar) represented the response. So it's usually best to either stick to req and res or request and response here. If you're unfamiliar with how requests and responses work, you should check out the Zapier API Tutorial.

If you remember our axios requests in React, we handle an object that comes back from the call that we typically save in a variable called response:

axios.get("some-url").then(response => {...});

Well now we're on the other side of the internet! The "req" parameter in our callback function in express is an object containing all kinds of information about the request that that client sent to us, the server. The "res" object is where we can add data and do any number of other things before we send it off back to the client who made the request. Above when we say res.send("Hello world!"), we're telling express to reply to the request immediately with just the string "Hello world!" as the response.

Conclusion

You've just built a server that can respond to a request! Granted, its a pretty useless server, but a server nonetheless. Express allows you the flexibility to organize your server's code any way you want (hence the tagline that calls it an "unopinionated framework"), but that still leaves it up to you, the developer, to organize things in a maintainable and logical fashion. One of the most common ways to do this is to organize your code into modules, but for now you should be proud that you wrote your first server using Node.js and express!