Handling Requests and Responses
Introduction
Handling requests and responses is a core function of any HTTP server. In this lesson, we’ll explore how to access request details and control the server’s response to different client requests. By understanding how to work with HTTP requests and responses, you’ll be able to build more dynamic and interactive web applications.
Understanding HTTP Requests
When a client sends a request to the server, it includes various details, such as the HTTP method, URL, headers, and optionally, a body with data. Understanding these components helps you determine the client’s intent and respond appropriately.
- Request Method: Specifies the type of operation the client wants to perform, such as
GET
,POST
,PUT
, orDELETE
. - Request URL: Indicates the endpoint the client is requesting.
- Request Headers: Provide additional information, like
Content-Type
,Authorization
, orUser-Agent
. - Request Body: Contains data sent with the request, typically used with
POST
andPUT
requests.
Accessing Request Information
To handle requests effectively, you need to access and interpret request details. Here’s how to retrieve some essential properties:
const http = require('http');
const server = http.createServer((req, res) => {
console.log(`Method: ${req.method}`);
console.log(`URL: ${req.url}`);
console.log(`Headers:`, req.headers);
res.end('Request details logged');
});
server.listen(3000, () => {
console.log('Server listening on port 3000');
});
This code logs the request method, URL, and headers whenever a request is made to the server.
Sending Responses to Clients
In Node.js, you can use the res
(response) object to send back data to the client. The response includes:
- Status Code: Indicates the result of the request (e.g.,
200
for success,404
for not found). - Headers: Provides metadata about the response.
- Body: Contains the data being sent back, such as text, HTML, or JSON.
Setting Status Codes
The HTTP status code tells the client if the request was successful or if an error occurred.
res.statusCode = 200; // Success
res.statusCode = 404; // Not found
res.statusCode = 500; // Internal server error
Setting the status code helps the client understand how to interpret the response.
Setting Response Headers
Headers provide additional context about the response. For example, setting the Content-Type
header ensures that the client knows the format of the response data.
res.setHeader('Content-Type', 'application/json');
Common headers include:
Content-Type
: Specifies the format of the response (e.g.,text/plain
,application/json
).Access-Control-Allow-Origin
: Controls cross-origin access for APIs.Content-Length
: Specifies the length of the response body.
Sending Different Types of Responses
1. Sending Plain Text
To send a simple text response, use res.end()
with a string:
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!');
2. Sending HTML Content
You can send HTML content by setting the Content-Type
to text/html
:
res.setHeader('Content-Type', 'text/html');
res.end('<h1>Hello, World!</h1>');
3. Sending JSON Data
For APIs, JSON is a commonly used format. Set the Content-Type
to application/json
and use JSON.stringify()
to convert the data to JSON.
res.setHeader('Content-Type', 'application/json');
const data = { message: 'Hello, World!' };
res.end(JSON.stringify(data));
Handling Different Routes and Methods
You can customize the server’s response based on the URL and method. Here’s how to handle different routes and methods in a basic routing example:
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/') {
res.setHeader('Content-Type', 'text/plain');
res.end('Home Page');
} else if (req.method === 'GET' && req.url === '/about') {
res.setHeader('Content-Type', 'text/plain');
res.end('About Page');
} else {
res.statusCode = 404;
res.end('404 Not Found');
}
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
In this code:
GET /
: Responds with "Home Page".GET /about
: Responds with "About Page".- Any other request responds with a 404 Not Found message.
Processing Request Body Data
For POST
requests, the client often sends data in the request body. To access this data in Node.js, you can listen for data
and end
events on the req
object:
if (req.method === 'POST' && req.url === '/data') {
let body = '';
req.on('data', chunk => {
body += chunk;
});
req.on('end', () => {
console.log(`Received data: ${body}`);
res.end('Data received');
});
}
This example collects data sent in the request body and logs it to the console.
Example: Simple HTTP Server with Request and Response Handling
Below is a complete example demonstrating how to handle requests and responses for different routes and methods:
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Welcome to the Home Page');
} else if (req.method === 'POST' && req.url === '/submit') {
let body = '';
req.on('data', chunk => {
body += chunk;
});
req.on('end', () => {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ message: 'Data received', data: body }));
});
} else {
res.statusCode = 404;
res.setHeader('Content-Type', 'text/plain');
res.end('404 Not Found');
}
});
server.listen(3000, () => {
console.log('Server running on port 3000');
});
Conclusion
In this lesson, you learned how to handle requests and responses in a Node.js HTTP server. By accessing request information and customizing responses, you can build versatile and interactive servers. With this knowledge, you’re ready to create more complex routes and handle different types of requests.