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, , which enables us to send responses back to the client. The object includes methods like , , and , for sending strings, JSON, and files, respectively.
