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() for sending strings, res.json() for sending JSON data, and res.sendFile() for sending files.
Best Practice: When sending JSON data (objects or arrays), always use res.json() rather than res.send(). While res.send() can work with objects, res.json() explicitly sets the correct Content-Type header and ensures proper JSON serialization.
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.
