Express Route Handlers
Let’s look at the details of routing so that we can practice.
We'll cover the following
In the previous lesson, we wrote the minimum code necessary to run the server and then accessed it through the browser.
Routes
Every application is usually divided into a bunch of routes. Any page or request we invoke on a website is hitting a specific route on the back-end server. Routes determine how each endpoint should be treated and what logic gets executed.
Each HTTP
request type is mapped to a routing method in Express with the syntax app.method(path, callback)
.
Route methods
The path defines the endpoint or the route path, for example, the / root
endpoint. After defining the endpoint, we then perform the matched callback
function. Here’s a list of the most common route methods:
- The
get
request handler is used to retrieve resources from the server. - The
put
request handleris used for creating and updating the data in the server. - The
post
request handler is used to create and update the data in the server. The basic difference betweenput
andpost
methods is thatpost
is used to create new objects, whileput
is used to update existing ones. - The
patch
request handler is used to update data in the server. The difference betweenput
andpatch
is thatpatch
is used to update one or two properties of a resource, whileput
is used to update all properties. - The
delete
request handler is used to remove a resource.
Route paths
As we discussed above, the path defines the endpoint that the request is connected to. Paths can be plain strings, string patterns, or regular (regex) expressions. The characters *
, +
, ?
, and ()
are considered a subset of the regular expressions set, although the -
and .
characters are interpreted literally as a string in the path.
Handlers
Route handlers
Node.js passes the request to Express, decides which route handler will process the request logic, and then returns a response.
Route handlers are the endpoints responsible for specific services. Here are some ways that route handlers might be used:
- We may use a route handler for authentication purposes. This route may be used to verify if a user exists in the database or not.
- We may use a route handler to register a new user and add them to the database.
- We may have a third route handler to upload a new item. We may need this route to enable the user to upload an image to their account.
Note: Use the
npm run start
command in the terminal below to run the application.
Get hands-on with 1400+ tech skills courses.