In our journey into the Express.js universe today, we are going to unravel requests and responses, which are critical for efficient web apps. Our aim is to make you comfortable with creating routes, handling requests, and sending responses in Express.js.
In Express.js, a client's request is accompanied by a request object (req
). The req
object holds data such as the URL, HTTP method, headers, and any data sent by the client.
For instance, to extract the URL and the User-Agent
header from the request in a GET method, we use req.url
and req.headers
respectively:
This logs the URL of a GET request as well as the request's User-Agent
header, and then sends a "Hello World!"
response to the client.
Along with req
, we also receive a response object, res
, which enables us to send responses back to the client. The res
object includes methods like res.send()
, res.json()
, and res.sendFile()
, for sending strings, JSON, and files, respectively.
For example, to respond with a JSON message, you would do the following:
We will explain JSON in more detail later in this lesson.
In Express.js, we define routes to respond to various URLs. These routes specify which HTTP methods they should respond to, such as GET, POST, and DELETE.
For instance, a route responding to a GET request at '/api/about'
looks like this:
This sends 'About page'
when a GET request is directed to the '/api/about'
endpoint.
JSON is a lightweight data interchange format used for data exchanges between servers and web apps. Express.js allows us to send JSON responses with the res.json()
method:
Using the code above, our Express.js server delivers a JSON response containing the items 'Shirt'
and 'Pants'
.
We are using a React app for our client-side interactions, which employs axios
to make HTTP requests to the Express.js server. If the API response is a raw string, the response.data
will store this raw string itself. However, if the Express.js API response is a JSON object, the response.data
will be a JSON object. Take a look at the example:
This axios
call fetches data from an endpoint upon loading and subsequently sets the 'items' state.
We've done a deep dive today, exploring requests and responses in Express.js and learning how to set up routes, handle requests, and send responses. Are you ready for some hands-on practice exercises? Practicing is the most surefire way to reinforce what you've learned. Great job today!
