Handling Requests and Responses
Handling Requests and Responses in Node.js
In any web server, handling HTTP requests and providing responses is a core task. Node.js provides the built-in http
module, which allows you to easily manage incoming requests from clients (such as browsers) and respond with data (like HTML, JSON, or other types). In this article, we will explore how to handle requests and responses using Node.js, including parsing request data, setting response headers, and sending appropriate responses.
Understanding HTTP Requests and Responses
Before diving into the Node.js code, let’s first understand the two key components that we will be working with:
- HTTP Request (req): This represents the data sent by the client to the server. It contains details like the request method (GET, POST), the URL being requested, headers, query parameters, body data (for POST requests), and more.
- HTTP Response (res): This represents the data the server sends back to the client. It includes a status code (such as 200 for success or 404 for not found), response headers (to describe the content type), and the actual content or data to be sent back to the client.
In Node.js, you work with these two objects (req
and res
) inside the callback function of an HTTP server.
Creating a Basic HTTP Server to Handle Requests
We will begin by creating a basic HTTP server that listens for incoming requests and sends responses. Here’s a simple example to set up a server that listens on port 3000:
const http = require('http');
const server = http.createServer((req, res) => {
// Set the response HTTP status code and headers
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
// Send the response body
res.end('Hello, this is your response!');
});
// Start the server and listen on port 3000
server.listen(3000, '127.0.0.1', () => {
console.log('Server running at http://127.0.0.1:3000/');
});
In this example:
req
is the request object that contains information about the incoming request.res
is the response object that is used to send a response back to the client.
Accessing Request Data
To make your server more dynamic, you often need to access data sent by the client in the request. This data can come from different sources:
- Request URL: The URL of the incoming request can be accessed through
req.url
. - Request Method: The HTTP method (GET, POST, etc.) is available through
req.method
. - Query Parameters: If the URL includes query parameters (like
?name=John&age=30
), you can parse them fromreq.url
. - Request Headers: The headers of the request can be accessed through
req.headers
. - Request Body: For POST or PUT requests, the request body contains data sent from the client (such as form data or JSON). Handling the request body requires reading data from the stream.
Handling Different HTTP Methods (GET, POST, etc.)
A common pattern in web servers is to handle different HTTP methods (such as GET, POST) in different ways. You can use the req.method
property to distinguish between different types of requests.
Here’s an example of how to handle GET and POST requests differently:
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'GET') {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('GET request received!');
} else if (req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk;
});
req.on('end', () => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end(`POST request received with data: ${body}`);
});
} else {
res.statusCode = 405; // Method Not Allowed
res.setHeader('Content-Type', 'text/plain');
res.end('Method Not Allowed');
}
});
server.listen(3000, '127.0.0.1', () => {
console.log('Server running at http://127.0.0.1:3000/');
});
In this example:
- GET Request: When the server receives a GET request, it simply responds with a message.
- POST Request: When the server receives a POST request, it listens for the data sent by the client. Using the
data
event on thereq
object, the server can accumulate the body data. Once the data is fully received, it sends back the response.
Handling Query Parameters
Often, data is passed through the URL as query parameters. In Node.js, query parameters are included in the req.url
property, but they need to be parsed manually or with the help of a module like url
or querystring
.
Here’s an example of handling query parameters:
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const queryParams = parsedUrl.query; // Extract query parameters
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end(`Received query parameters: ${JSON.stringify(queryParams)}`);
});
server.listen(3000, '127.0.0.1', () => {
console.log('Server running at http://127.0.0.1:3000/');
});
When a request is made to http://127.0.0.1:3000/?name=John&age=30
, the server will respond with:
Received query parameters: {"name":"John","age":"30"}
Sending JSON Responses
Many modern web applications need to send and receive JSON data. You can set the Content-Type
header to application/json
and send JSON data as the response.
Here’s an example:
const http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'GET') {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
const responseObject = { message: 'This is a JSON response!' };
res.end(JSON.stringify(responseObject));
} else {
res.statusCode = 405;
res.setHeader('Content-Type', 'application/json');
const errorResponse = { error: 'Method Not Allowed' };
res.end(JSON.stringify(errorResponse));
}
});
server.listen(3000, '127.0.0.1', () => {
console.log('Server running at http://127.0.0.1:3000/');
});
This will respond with:
{
"message": "This is a JSON response!"
}
Conclusion
In this article, we’ve explored how to handle HTTP requests and responses in Node.js. We’ve covered how to:
- Create a basic HTTP server using the
http
module. - Access request data such as query parameters, method types, and body content.
- Handle different HTTP methods (GET, POST).
- Send various types of responses, including plain text and JSON.
Handling requests and responses is the foundation of building web applications, APIs, and services with Node.js. By mastering these concepts, you can start building more complex and dynamic server-side applications.