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.
By the end of this tutorial, you will be able to:
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.
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' }
.
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.
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' }
.
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.
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.
Try to explore more properties and methods of req
and res
in the Express.js documentation.
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 /login
and 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.