Express: What’s It Doing? In a Nutshell …

Let’s walk through an app and talk about all of it’s parts. Since there’s a lot of details, I’m going to stick to bullet-point format and walk through each line of code, putting explanations in layman’s terms. Here we go!

Here’s our app:

var express = require('express')

Remember: we’re using Nodejs, which is sufficient on it’s own to create a web app. Express is a framework built upon it, something we install using npm. Requiring it here is what makes this an Express application.

require('express') is a node function, which is why it has the familiar parentheses and quotes. Express is the module being required, giving us access to all of it’s methods and functions. Also, we named our var express but we could have named this foofoo if we wanted. It’s just a variable.

var app = express()

This is an instance of the express module we just required. When we’re creating routes, we call a new instance of express to run it. We’ll preface our routes with app and then call a function on them.

app.get(path, callback(args){instructions})

app  is an instance of express. .get  is a function (sometimes called a method) that requires a path and callback. That callback is the handler for the route, which are the instructions for what to do with the route. The handlers contain the HTTP request (req) and response(res).

  function(req, res) {}

This is our handler and it has two parts: a request and a response. After we’ve told Express (app) to get the path (web page), our handler carries any necessary information back to the server as a request. req  is an HTTP request. Requests are usually objects of data. For example, the DOM is just a giant object. The webpage is the object requested in this case.

When we see req.params  or req.body , both params and body are objects with data inside. Think about how they’re used. Everytime a webpage is requested, the data on that page is sent as an object. That’s how we’re able to access that data with things like req.params and bodyParser. The HTTP request carries that data to the server and we get to set the instructions for responding to it.

res.send('Hello World!')

The response is the second part of the instructions for the handler. So far, we’ve created an instance of express, asked it to get a path and then created a callback which tells us what to do when that path is accessed.  res  is short for response. In this case, the client will be sent the string ‘Hello World!’.

The remainder of code on our app are just variables for starting our Express server. Nodejs has it’s own functions to help make it easier for us to get common information. In this case server, address, and port are clear functions which return the same.

Leave a Reply

Your email address will not be published. Required fields are marked *