The Basics Of The Express Framework
What Is Express?
npm install --save express
Once this finishes you should see an entry added to your dependencies within your package.json file with the version of express you installed. You will then go to the top of your application (in this example app.js is the top of our application) and remove any routes you have along with what you used within createServer. In order to begin using express you will need to require it near the beginning of the top of your application and set it to a variable. You will then set another variable to the return of the call for your first variable. This latest variable is a valid request handler and can be used to handle and respond to http requests. If this is as confusing as it sounded while I typed it out…here is a picture of the top of a small NodeJS application which uses Express:
The additional utility this affords you is that you can now ‘use’ simple http request methods when you define your routes. We will go over how this is done in greater detail within the next section. Now that we have some of the basics covered lets put it all together with a very simple example!
One of the advantages Express provides is the ability to use multiple middleware functions that handle a request object, a response object, and the next middleware function. These middleware functions are used to handle multiple routes. In order to better visualize this lets go back to our single page application using Express that displays ‘Hello Express World!’. If we added another response for the same route we can do so using the next function like so:
If we were to add multiple routes to our app the order in which we add them matters in that it is ‘first come first serve’. The documentation on routing is a good place to start for understanding this process. It is best practice to place your routes in a routes folder and export them like so:
You would then import these routes and set them to a variable at the top of your app. After doing this you can pass these routes as a middleware function like so:
Just for a bit of clarity here is a screen grab of the new /users middleware route that is just a very simple form:
At this point we have a multi route page! Hopefully this has provided a great first glance at what the Express framework is and how to use it. There is of course a lot more that this framework can do. Feel free to checkout the documentation if you would like to look at some of these features yourself. I will focus on additional features Express provides us in future blog posts.