Skip to content

Instantly share code, notes, and snippets.

@jimdel

jimdel/blog.md Secret

Created February 1, 2018 04:19
Show Gist options
  • Save jimdel/8b98ca157950e4ee558a87f4ad785666 to your computer and use it in GitHub Desktop.
Save jimdel/8b98ca157950e4ee558a87f4ad785666 to your computer and use it in GitHub Desktop.

Express Tutorial

Introduction

Hello and welcome! If you are reading this article that means you are interested in learning a little bit about an awesome HTTP web framework called Express. My goal with this article is to briefly introduce Express and then review the process of configuring the boilerplate code and creating a few basic routes to demonstrate how Express works. As per the documentation website: "Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications." Web frameworks allow developers to build highly customizable back-ends for web applications and Express is one of the best!

So let's get started!

Configuration

The first step in configuring our Express applicaiton is to create a new local project directory and create an index.js file. You can name the directory and file whatever you like. After the directory and file are created we need to intialize the directory as a node project. We can do this by using the command npm init -y. The -y sets all the prompts that node will ask you to configure to the default setting. If you want to customize your node project configuration you can simply leave out the -y flag and you'll have the ability to name your project, give it a version, and do some other cool stuff. For our purpose the default settings will work just fine. The next step is to npm install express. This process will give us the ability to import Express into our node project. After the installation and configuration process is complete we want to write the following lines of code.

https://gist.github.com/b73e4aea6ce7cfe2ccdba7adf5e916ab

Here we are first importing Express from the node module we just installed and subsequently instantiating Express in our newly created app variable. This instantiation means that our app variable is now an Express object instance Our app instance is chained to the Express prototype with access to all of it's properties and methods. Once we have completed these two steps we can move on to configuring our Express server to start listening for all incoming requests. These HTTP requests, which come from the client, tell our server to do certain things like serve up information from a database or make API calls. To have our app listen we write the following code.

https://gist.github.com/48d0a56089337c7c1dc3a7962e7551f3

These lines of code are essentially saying, "Okay, I am now listening on port 8080 for HTTP requests so I can give you back some cool data!" I believe the port number to listen on is usually 8080 as per convention but it's important to note that we are using a variable in the actual listening function. It makes it very easier to change the port by changing the variable value if you ever decide to deploy your application. For more information about Ports see this page.

So now that we have our app listening we can write some middleware functions! However before we begin coding we should take a moment to understand the flow of information in Express. I like to think of it as an old penny drop game.

The HTTP requests come in from the 'top' then fall through and hit each piece of middleware until they hit their final end point: the route. Middleware are functions that "have access to the request object, the response object" from the HTTP requests and can perform actions on those objects. The request object is a piece of information coming from the client that asks for some information and as you can guess the response object is our response to that request. Some common actions that can be performed on these objects are: executing code, making changes to these objects, and logging useful information to the console which aids in debugging.

One great thing about Express is that many developers have written extremely usefil middleware node modules that we can import and use in our project. Two great middleware modules that I use in many of my projects are body parser and volleyball. Body parser parses the incoming requests and converts them to JSON so we can easily manipulate them. Volleyball is a useful logging tool that will log the status of our requests. To use these middleware modules we need to npm install them and import them into our project.

npm install body-parser volleyball

https://gist.github.com/fd71cc0b95203c5238a4e0af7a37e078

Now that we have them imported we can configure them using app.use(). This tells our Express app to run these middleware functions on all incoming requests and outgoing response.

https://gist.github.com/e5b33cbdfca35b1a4e34ed28bc129f98

It's important to place these few lines of code under where we instantiated Express in our app and above where our server is listening. This ensures that the first thing that the incoming requests will hit are our middleware functions (think of the penny game). We can also write our own middleware functions that can communicate with the incoming request and response object. We will be writing one of our own shortly.

Now for the fun part: routes! There are four basic request types that a client will send our server: GET, POST, DELETE, PUT. GET is a request for information, POST is a request to post information in the database, DELETE is a request to delete information from the database, and PUT is a request to update information in the database. Express let's us design routes to handle these incoming request types. For the sake of brevity I'll only be covering how to write a GET route to serve information to the client. It's also very important to place all routes below middleware functions and above where our server is listening. Again, think of the penny falling game. We want all of our middlware functions to be hit before our request gets to the end route. Here is some code for a GET route:

https://gist.github.com/944435b957be6ee6946b476bfe49f25d

The above route is handling GET requests for the URI '/cake'. If a request from the frontend is coming in and is looking for '/cake' we can respond accordingly. We design the function using (req, res, next) which means it's taking in the request and response objects as parameters, sees that the request object is looking for /cake, and then telling the response object to send back Here is some chocolate cake!.

As you noticed we are also using the next parameter. This is for our middleware. All middleware must be chained together so the request can flow from middleware to middleware without being lost in cyberspace. We ensure this linkage using next. A lot of node middleware modules, like volleyball and body parser, are written with next in their source code so they keep the middleware linked together. We will use next to ensure errors get passed along down the chain. Speaking of errors, what will happen if there is no chocolate cake to serve back to the clients?

https://gist.github.com/d433d921c7c4e57c73cd31a74bffb694

In this scenario the request is coming in and looking to be served /cake. Great! We have a route to handle that! Unfortunately, we don't have anymore chocolate cake so we enter the else case and create an error. This error is then passed to an error handling middleware function, using next, so we can alert the client that we have no more chocolate cake. Now we need to create our error handler. If we omit this error handler our incoming requests could hang and crash our application, so let's code it:

https://gist.github.com/3a94c85d3259b70241791f40b794f3c6

Above is an example of a basic error handler. One important thing to note is that all error handling middleware have four parameters: err, req, res, next. The err is an incoming error, the req & res are the request and response objects,and the next is the middleware link connecting our error handler to the upstream middleware and route functions. Only error handling middleware have four parameters, if we tried to write another middleware function that didn't handle errors but had four parameters we would run into trouble.

In our code the error is coming in and being logged to the console using console.error. We will see the error message and a stack trace in the console allowing us to track down and see where the error is occuring. In our case we would see this error message: 'Sorry, there is no chocolate cake!' and know that our error occured in our GET route.

I hope you enjoyed this article! Please drop me a line if you see any glaring errors or suggestions for improvement. I'd love to keep this updated so it can serve as a basic guide for newcomers looking to learn about Express. Also let me know if you'd like me to cover more advanced Express functionality or any of the other methods (POST, PUT, DELETE) that I haven't covered here.

Thank You and Happy Coding!

SOURCES Express Docs: https://expressjs.com/ Node Project: https://docs.npmjs.com/getting-started/creating-node-modules Prototypal Inheiritance: https://medium.com/@kevincennis/prototypal-inheritance-781bccc97edb Computer Ports: https://en.wikipedia.org/wiki/Port_(computer_networking) Image: http://media.liveauctiongroup.net/i/5124/7807349_1.jpg?v=8CA37330309A700

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment