Express.js Demystified
Introduction
If you know about or are into web development with Node.js, you’ve probably heard of Express.js. If you haven’t or want a more thorough understanding of the framework this is the right blog for you! Express is a cool framework that will help you build apps and APIs quickly and with ease. It’s open-source too, meaning you can customize it however you like, making it the perfect tool for being creative with web applications that fit your needs.
By far one of its best features is its routing system, which makes it easy to create well-organized routing structures for your web applications. Throughout this read, I’ll supply you with interesting insights on said routing along with other “need to knows” such as basic setup for express.js, middleware, and Controllers.
Express.js works great with other Node.js libraries, so there's no worrying about compatibility issues. The community is also large and active, so you’ll always find plenty of support and resources to help you along the way just like I did. It’s used by developers of all skill levels for projects of all sizes. Some websites that have been created using express.js are MySpace, PayPal, GoDaddy, and many more! Whether you’re a seasoned developer or just starting out, Express.js is a great tool to have in your web development arsenal.
Setting up Express.js
Assuming you’ve already downloaded Node.js from the browser (if you haven’t here's a link node.js) then setting up Express.js is relatively easy and can be done in just a few steps. The first thing you’ll want to do is install the framework by running the following command into the terminal:
npm install express
Now that you’ve installed Express.js, you need to make a folder structure. Do this by creating a new folder for your project and inside the folder, create a javascript file and name it whatever you’d like. The most common naming conventions though are “index.js” or “app.js”. This file will be the entry point for your application
Next, you’ll need to require the Express.js module and create an instance of the express app. Here’s an example of how you can do that:
const express.require('express')
const app = express()
Now with the Express application created, we can create our routes. Routes are URL paths the server will respond to but I’ll touch more on this shortly. Here’s an example of the most basic route that returns “Hello World” when the user accesses the homepage:
app.get('/', (req, res) => {
res.send('Hello World')
})
Finally, you’ll need to start the server by telling the Express.js application to listen on a specific port. Here’s an example of doing so:
app.listen(3000, () => {
console.log('Server started on port 3000')
})
That’s it! With these simple steps, you can have a basic Express.js application up and running in no time.
Routing
A route is simply a way to map an HTTP request to a specific function that will handle the request and send a response back to the client.
To set up a basic route in Express.js you use the “app.get()” method which will take in two parameters: The route path and a callback function that will handle the request. Here’s an example of this
app.get('/hello', (req, res) => {
res.send('Hello World')
})
This is exactly what we did earlier while setting up the basic route for our server except in this case were setting up a route for “/hello” instead of the base directory “/”. When a user visits the ‘“hello” route, Express.js will call the callback function and send the string “Hello World” back to the client.
Express.js also provides support for more dynamic routes, where route parameters can be used to create more flexible and customizable routes. Here’s an example:
app.get('/users/:id', (req, res) => {
const userId = req.params.id
res.send(`User ID: ${userId}`)
})
In this example, the route “/users/:id” will match any URL that starts with “users/” and has a parameter named “id”. The “req.params” object is used to retrieve the value of the “id” parameter, which is then sent back to the client in the response.
Additionally, “app.get()” isn’t the only HTTP method Express.js provides, it also provides “app.post()”, “app.put()”, “app.delete()”, etc. to support different types of requests and ultimately allowing you to create CRUD apps.
Middleware
Middleware is one of the key features in Express.js that allows you to add different functionalities to your application’s request-response cycle. Middleware functions are functions that have access to the request object (“req”), and the response object (“res”) and can be used to do all sorts of things, such as logging, error handling, authentication, and more.
Whenever a request is made to your app, it goes through a series of middleware functions before finally getting handled by the appropriate route. Each middleware function can modify the request and response objects before passing control on to the next middleware function using the “next()” function.
Here’s an example of a simple middleware function that logs the URL of the incoming request to the console:
const logRequest = (req, res, next) => {
console.log(`Someone visited ${req.url}!`)
next()
}
In this example, “logRequest” is a simple middleware function that logs the URL of the incoming request to the console. To use this middleware in your application, you would simply add it to the chain of middleware functions using the “app.use()” method:
app.use(logRequest);
Using middleware can lead to so many advantages in web development. By easily adding and removing functionality to your application’s request-response cycle makes this alone such a powerful tool for creating flexible and robust web applications
Controllers
In most Express.js apps we use a pattern called Model-View-Controller (MVC) to structure our code. The “M” stands for model, which will represent the data and business logic of your application. The “V” stands for view, which is responsible for rendering the interface to the user. Lastly the “C” stands for controller, which handles user input and controls the flow of your application.
Controllers are JavaScript modules that contain the logic for handling requests and sending responses back to the client. The reason we would use controllers is to isolate the request-handling logic from the rest of your application so that we can focus more on the individual peices which makes it easier to maintain and test.
When creating a controller in Express.js, you typically create a new JavaScript file and define a set of functions that will handle requests for a particular set of routes. Each function in the controller is responsible for handling a specific type of request and returning a response to the client.
For example, here’s a simple controller that handles requests for a route to “/users”:
const getUser = (req, res) => {
// Get a user from database
res.send(user)
}
const createUser = (req, res) => {
// Create a new user in database
res.send('User created successfully!')
}
module.exports = {
getUser,
createUser
}
In this example, we define two functions in our controller: “getUser” and “createUser”. Each function handles a specific type of request for the “/users” route, and sends an appropriate response back to the client.
All in all controllers are an essential aspect in creating express.js apps as it makes it much easier to manage and test your application, and keep your request-handling logic separate from your data and view logic.
Conclusion
To wrap things up, we’ve covered some of the key features of Express.js. We started by looking at how to set up an Express.js app, including installing the necessary dependencies and creating a basic server. We also talked about routing in Express.js, which is how you can define the different URLs and endpoints for your app.
Next, we checked out middleware, which is basically a way to add extra functionality to your app’s request-response cycle. Middleware functions are just JavaScript functions that can do things like logging, error handling, and authentication. They’re really cool and can make your life easier as a developer.
Finally, we discussed the controller structure in Express.js, which is a way to organize your code and separate your request-handling logic from your data and view logic. Controllers are JavaScript modules that handle requests for a particular set of routes, and they can make your app much easier to maintain and test.
Overall, Express.js is a powerful tool that can help you build awesome web apps with Node.js. It might seem a bit overwhelming at first, but with a bit of practice and some experimentation, you’ll be able to create amazing apps in no time!