Express: A Popular Node.js Framework
Express is a widely used Node.js web framework that provides easy-to-use functionality for building web servers. It builds on top of the features of Node.js and satisfies the needs of the web server use-case.
Introduction to Express
Express is a Node.js web framework that is built on top of the powerful networking tool, Node.js. It offers an easy-to-use and performant solution for building web servers. It is open source, free, extensible, and provides a wide range of pre-built packages for various functionalities.
Installation
You can install Express into any project using npm or Yarn.
To install Express using npm:
1 | npm install express |
To install Express using Yarn:
1 | yarn add express |
Both of these commands can be used in an empty directory when starting a project from scratch. You can also use them in an existing project.
Hello World
To create your first Express web server, follow these steps:
- Create an
index.js
file in your project’s root folder. - Write the following code in the
index.js
file:
1 | const express = require('express') |
- Save the file and start the server by running the following command in your terminal or command prompt:
1 | node index.js |
- Open your web browser and navigate to
http://localhost:3000
. You should see the message “Hello World!” displayed.
This simple code creates an Express application, listens for GET requests at the root URL (“/“), and sends the response “Hello World!” to the client.
Learn the basics of Express by understanding the Hello World code
The Hello World code in Express demonstrates some important concepts.
Importing the Express package: We import the Express package using
require('express')
and assign it to the variableexpress
.Creating an application: We create an application by invoking
express()
and assigning the returned application object to the variableapp
.Handling a GET request: We use the
app.get()
method to handle GET requests at the root URL (“/“). This method takes a callback function that is executed when a request is received. In the Hello World code, the callback function sends the response “Hello World!” to the client.Starting the server: We start the server by calling the
app.listen()
method, which listens for incoming connections on port 3000. We pass a callback function toapp.listen()
to log a message when the server is ready to accept new requests.
By understanding this Hello World code, you can start building more complex Express applications and explore the various features and functionalities it offers.
Request parameters
In Express, the Request
object contains all the information related to an HTTP request. You can access different properties of the Request
object to retrieve request parameters, headers, cookies, and more. Some commonly used properties of the Request
object are:
req.params
: Contains named parameters from the route path.req.query
: Contains the query string parameters from the URL.req.body
: Contains the data submitted in the request body (needs to be parsed and populated manually).req.headers
: Contains the HTTP headers of the request.req.cookies
: Contains the cookies sent by the client.req.hostname
: Represents the hostname as defined in the Host HTTP header value.req.method
: Represents the HTTP method used.req.path
: Represents the URL path of the request.req.protocol
: Represents the protocol used for the request (e.g., “http” or “https”).req.ip
: Represents the client’s IP address.req.secure
: Represents whether the request is secure (uses HTTPS).req.xhr
: Represents whether the request is an XMLHttpRequest.
These properties allow you to access and process different aspects of the request to customize your application’s behavior.
Sending a response
In Express, the Response
object represents the HTTP response that is sent back to the client. You can use various methods of the Response
object to send a response to the client. Some commonly used methods are:
res.send()
: Sends a string response to the client.res.json()
: Sends a JSON response to the client.res.end()
: Sends an empty response to the client.res.set()
: Sets any HTTP header value.res.cookie()
: Sets a cookie in the response.res.status()
: Sets the HTTP response status code.res.redirect()
: Performs a redirect to another URL.res.download()
: Sends a file to be downloaded.res.sendStatus()
: Sends a response with a specific status code.
These methods provide flexibility in how you send responses to your clients based on different scenarios.
Send a JSON response
To send a JSON response using Express, you can use the res.json()
method. This method accepts an object or an array, converts it to JSON format, and sends it as the response to the client. Here’s an example:
1 | res.json({ username: 'Flavio' }) |
Use res.end()
to send an empty response
If you want to send an empty response without any body content, you can use the res.end()
method. This method terminates the response without sending any content. Here’s an example:
1 | res.end() |
Change any HTTP header value
You can change any HTTP header value using the res.set()
method. This method allows you to set custom header values. Here’s an example:
1 | res.set('Content-Type', 'text/html') |
There is a shortcut for setting the Content-Type
header:
1 | res.type('.html') // returns 'text/html' |
Set cookies
To set cookies in the response, you can use the res.cookie()
method. This method sets a cookie in the response header. You can also specify various options for the cookie, such as domain, expiration date, HTTP only, and more. Here are some examples:
1 | res.cookie('username', 'Flavio') |
You can also clear a cookie using the res.clearCookie()
method:
1 | res.clearCookie('username') |
Set the HTTP response status
To set the HTTP response status code, you can use the res.status()
method. This method allows you to set the status code of the response. Here’s an example:
1 | res.status(404).end() |
There is also a shortcut method called res.sendStatus()
:
1 | res.sendStatus(200) // returns 'OK' |
Handling redirects
To perform a redirect to another URL, you can use the res.redirect()
method. This method allows you to specify the target URL and the status code of the redirect. Here are some examples:
1 | res.redirect('/go-there') |
Send a file to be downloaded
To send a file to be downloaded by the client, you can use the res.download()
method. This method allows you to specify the file path and an optional filename that will be presented to the user. Here are some examples:
1 | res.download('/file.pdf') |
Support for JSONP
JSONP (JSON with Padding) is a technique to consume cross-origin APIs from client-side JavaScript. Express provides support for JSONP through the res.jsonp()
method. This method accepts an object or an array, converts it to JSON format, and handles JSONP callbacks. Here’s an example:
1 | res.jsonp({ username: 'Flavio' }) |
JSONP can be useful when working with client-side JavaScript that needs to communicate with cross-origin APIs.
Routing
In Express, routing refers to defining routes that handle incoming requests at specific URLs. You can define routes in Express using the app.get()
, app.post()
, app.put()
, app.delete()
, and app.patch()
methods, depending on the HTTP method of the request. These methods accept a URL pattern and a callback function to handle the request. Here’s an example:
1 | app.get('/user/:id', (req, res) => { |
Named parameters
You can use named parameters in the URL pattern to capture dynamic values from the URL. These named parameters are accessible through the req.params
object in the callback function. Here’s an example:
1 | app.get('/user/:id', (req, res) => { |
In this example, the id
parameter is captured from the URL and can be accessed using req.params.id
.
Use a regular expression to match a path
In Express, you can use regular expressions to define routes that match multiple paths. By using regular expressions, you can handle multiple URL patterns with a single route definition. Here’s an example:
1 | app.get(/post/, (req, res) => { |
In this example, the route will match URLs that contain the word “post” anywhere in the path.
Middleware
Middleware functions in Express are functions that are executed in the request-response cycle before the final route handler is called. Middleware functions can be used to modify the request or response objects, terminate the request, or perform any other operations necessary for your application. In Express, middleware functions are added to the execution stack using the app.use()
method. Here’s an example:
1 | app.use((req, res, next) => { |
In this example, the middleware function takes three parameters: req
(request), res
(response), and next
(a reference to the next middleware function in the stack). Middleware functions must always call the next()
function to pass the control to the next middleware in the stack. If no next()
function is called, the request will be terminated.
Middleware functions can be used for various purposes, such as logging, authentication, error handling, and more. There are also many pre-built middleware functions available in the form of npm packages that you can use in your Express application.
Serving static assets
In Express, you can serve static assets such as images, CSS files, and JavaScript files by using the express.static()
middleware. This middleware function serves static files from a specified directory or path. To use this middleware, you need to specify the directory or path where your static files are located. Here’s an example:
1 | app.use(express.static('public')) |
In this example, the public
folder contains all the static assets, and they will be served at the root level of the application. For example, if you have an index.html
file in the public
folder, it will be accessible at http://localhost:3000/index.html
.
This functionality is useful for organizing and serving static assets in your Express application.
Templating
Express supports server-side templating to generate dynamic HTML content. By using a templating engine, you can render views dynamically based on data received from the server. Express has support for various templating engines, such as Jade, Pug, Mustache, EJS, and more. To use a templating engine in Express, you need to set it as the view engine and specify the directory where your views are located. Here’s an example using the Handlebars templating engine:
1 | app.set('view engine', 'hbs') |
In this example, we configure Express to use the Handlebars templating engine by setting the view engine to 'hbs'
. We also specify the about
view to be rendered when a request is made to the /about
URL. The second argument to the res.render()
method is an object that contains the data to be passed to the template. In this case, we pass a name parameter with the value 'Flavio'
.
By using templating engines, you can create dynamic views in your Express application and customize the content based on the data received from the server.
What’s next?
Express is a powerful web framework that provides a wide range of features and functionalities. It empowers you to build complex web applications by leveraging the capabilities of Node.js and integrating with various databases, caching systems, and more. With Express, the possibilities for building scalable and performant web servers are limitless.
Tags: Express, Node.js, web framework, routing, middleware, templating, HTTP, JSON, cookies, static assets