What is Express, and how can we use it?
If you’re a full-stack developer, and trying to make a full-stack application through Node.js, Express will make your life 100x easier. If you don’t know what Express is, it’s what Ruby-on-Rails/Sinatra is to Ruby, or what Django is to Python.
Express is a light-weight web application framework to help organize your application into an MVC architecture on the server side. It’s also the most popular Node framework, and is the underlying library for other popular Node web frameworks. Usually Express is paired with MongoDB, but can also be paired with whatever database your heart desires. If you’ve ever heard of the MEAN stack, or MERN stack, both of those include the use of Express. MEAN stack roughly translates to:
MongoDB - Used as a document-based NoSQL database.
Express.js - Web framework for Node.js.
Angular - Front-end web framework.
Node.js - Js runtime environment for implementing the application back-end in Js.
As opposed to MEAN, the MERN stack translates to:
MongoDB - Used as a document-based NoSQL database.
Express.js - Web framework for Node.js.
React - Front-end library for UI development.
Node.js - Js runtime environment for implementing the application back-end in Js.
How can Express make your life easier with node?
With Express being implemented with Node, we can do the following:
- Allows to set up middlewares to respond to HTTP Requests.
- Defines a routing table which is used to perform different actions based on HTTP Method and URL.
- Allows to dynamically render HTML Pages based on passing arguments to templates.
- Can decrease the amount of code that is written compared to vanilla Node.js
and much more!
Here’s an example of how having Express makes your life easier. I will set up a basic route in vanilla Node, and then compare it to code written with Express.
As we can tell, the two of them look different. In the vanilla Node, we require the http module and then we create a server with it, including the header, and then we end the response by utilizing res.end().
Express on the other hand, requires you to require the express module, followed by saving the express application into another variable, and invoking it. We also then make a simple GET request, and the response we send is “Hello World” when we land on the homepage. Finally, we utilize the app.listen(8000); for the port we want to be on. Notice how we didn’t have to write out the header? That’s because Express manually does that.
I hope this blog helps you understand Express more, and why you should use it if you’re using Node, and want an entire Full-Stack application made out of Js, and how it will make your life 100x easier.