Express.js / Handling Requests and Responses
Working with Request and Response Objects
In this tutorial, you will learn how to work with request and response objects in Express. This includes understanding their properties and methods, and how to use them to handle …
Section overview
5 resourcesExplores working with request and response objects in Express.
1. Introduction
In this tutorial, we will delve into the world of web development using Express.js, a popular framework for Node.js, by learning about Request and Response objects.
Objective
- Understand the concepts of Request and Response objects in Express.js
- Learn how to utilize their properties and methods in handling HTTP requests and responses
Learning Outcomes
By the end of this tutorial, you will be able to:
- Explain the role of Request and Response objects in Express.js
- Use the properties and methods of Request and Response objects
- Handle HTTP requests and responses effectively
Prerequisites
- Basic knowledge of JavaScript
- Familiarity with Node.js and Express.js
2. Step-by-Step Guide
In Express.js, req (request) and res (response) are objects that encapsulate client request and server response, respectively. They contain a wealth of information and methods needed in web development.
Request Object
The request object (req) represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on.
Example:
app.get('/user/:id', function(req, res) {
console.log(req.params);
res.send('User Info');
});
In the example above, req.params is used to retrieve the route parameters. When you navigate to /user/42 in your browser, it will log { id: '42' }.
Response Object
The response object (res) represents the HTTP response that an Express.js app sends when it gets an HTTP request. It has methods for sending HTTP responses such as res.send(), res.json(), res.render(), etc.
Example:
app.get('/', function(req, res) {
res.send('Hello World');
});
In the example above, res.send() is used to send a response back to the client.
3. Code Examples
Example 1: Using req.query
// Assuming you're running on localhost:3000
app.get('/search', function(req, res) {
console.log(req.query);
res.send('Search Results');
});
When you navigate to localhost:3000/search?keyword=express, the console will log { keyword: 'express' }.
Example 2: Using res.json()
app.get('/api/data', function(req, res) {
const data = { name: 'John', age: 25 };
res.json(data);
});
In the example above, res.json() is used to send a JSON response. Navigating to localhost:3000/api/data will show { "name": "John", "age": 25 } in the browser.
4. Summary
In this tutorial, we have learned about the Request and Response objects in Express.js and their common properties and methods. You're now able to handle HTTP requests and responses effectively.
Next Steps
Try to explore more properties and methods of req and res in the Express.js documentation.
Additional Resources
5. Practice Exercises
-
Exercise 1: Create an Express.js application that responds with the user's IP address and browser information when visited at
/info. -
Exercise 2: Create an Express.js application that accepts POST requests at
/loginand responds with a success message if the username and password are correct. -
Exercise 3: Create an Express.js application that serves JSON data of all the users when visited at
/api/users.
Note: For these exercises, you might need to install additional middleware like body-parser to parse incoming request bodies. Also, to test POST requests, you can use tools like Postman.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article