Nodejs Http Module
[Node.js Built-in Modules](#)
* * *
The `http` module of Node.js is one of the core built-in modules, allowing developers to create HTTP servers and clients. With this module, we can easily handle HTTP requests and responses, building web applications or API services.
The `http` module provides the ability to create servers and initiate HTTP requests, forming the foundation for building web applications. It supports the HTTP/1.1 protocol and offers a rich set of APIs for handling various HTTP-related operations.
* * *
## Creating an HTTP Server
Creating a server using the `http` module is very straightforward. Below is a basic example:
## Example
```javascript
const http = require('http');
// Create an HTTP server
const server = http.createServer((req, res) => {
// Set response headers
res.writeHead(200, {'Content-Type': 'text/plain'});
// Send response data
res.end('Hello, World!n');
});
// Listen on port 3000
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
### Code Explanation
1. `require('http')` - Imports the Node.js `http` module.
2. `http.createServer()` - Creates an HTTP server instance.
3. Callback function `(req, res) => {...}` - Handles each HTTP request.
* `req` - The request object, containing information sent by the client.
* `res` - The response object, used to send responses back to the client.
4. `res.writeHead()` - Sets the response headers.
5. `res.end()` - Ends the response and sends the data.
6. `server.listen()` - Starts the server listening on the specified port.
* * *
## Handling HTTP Requests
An HTTP server needs to be able to handle different types of requests. Let's see how to parse request information:
## Example
```javascript
const http = require('http');
const server = http.createServer((req, res) => {
// Get the request method, URL, and headers
const { method, url, headers } = req;
// Log the request information
console.log(`Received ${method} request, path: ${url}`);
console.log('Request headers:', headers);
// Handle based on the request method
if (method === 'GET') {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('This is a GET requestn');
} else if (method === 'POST') {
let body = '';
// Collect POST data
req.on('data', chunk => {
body += chunk;
});
// Data collection complete
req.on('end', () => {
console.log('POST data:', body);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Data receivedn');
});
} else {
res.writeHead(405, {'Content-Type': 'text/plain'});
res.end('Method not allowedn');
}
});
server.listen(3000);
### Common Properties of the Request Object (`req`)
- `req.method`: The HTTP request method (e.g., GET, POST, PUT, DELETE).
- `req.url`: The requested URL path.
- `req.headers`: The request header object.
- `req.httpVersion`: The HTTP protocol version.
### Common Methods of the Response Object (`res`)
- `res.writeHead(statusCode, headers)`: Sets the response status code and headers.
- `res.write(data)`: Writes data into the response body.
- `res.end()`: Ends the response, optionally sending final data.
- `res.setHeader(name, value)`: Sets a specific response header.
* * *
## Making HTTP Requests
The `http` module can not only create servers but also act as a client to make HTTP requests:
## Example
```javascript
const http = require('http');
// Make a GET request
http.get('http://jsonplaceholder.typicode.com/posts/1', (res) => {
let data = '';
// Receive data
res.on('data', (chunk) => {
data += chunk;
});
// Data reception complete
res.on('end', () => {
console.log('Response data:', JSON.parse(data));
});
}).on('error', (err) => {
console.error('Request error:', err);
});
### Making a POST Request
## Example
```javascript
const http = require('http');
// Request options
const options = {
hostname: 'jsonplaceholder.typicode.com',
port: 80,
path: '/posts',
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
};
// Create the request
const req = http.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('Response:', JSON.parse(data));
});
});
// Handle errors
req.on('error', (err) => {
console.error('Request error:', err);
});
// Write request data
const postData = JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
});
req.write(postData);
req.end();
* * *
## Practical Use Cases
### 1. Creating RESTful APIs
## Example
```javascript
const http = require('http');
const server = http.createServer((req, res) => {
const { method, url } = req;
// Simple routing logic
if (method === 'GET' && url === '/api/users') {
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify([{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]));
} else if (method === 'POST' && url === '/api/users') {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
const newUser = JSON.parse(body);
// Save to database here
res.writeHead(201, {'Content-Type': 'application/json'});
res.end(JSON.stringify({ id: Date.now(), ...newUser }));
});
} else {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Not Foundn');
}
});
server.listen(3000);
### 2. Proxy Servers
## Example
```javascript
const http = require('http');
const proxy = http.createServer((clientReq, clientRes) => {
// Forward request to target server
const options = {
hostname: 'example.com',
port: 80,
path: clientReq.url,
method: clientReq.method,
headers: clientReq.headers
};
const proxyReq = http.request(options, (proxyRes) => {
// Forward response from target server to client
clientRes.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(clientRes);
});
// Forward client request body
clientReq.pipe(proxyReq);
});
proxy.listen(8080);
* * *
## Best Practices
1. **Error Handling**: Always handle errors in both requests and responses.
2. **Performance Considerations**: For high-concurrency applications, consider using connection pools.
3. **Security**:
* Validate all inputs.
* Set appropriate security headers.
* Limit the size of request bodies to prevent DoS attacks.
4. **Use Streams**: For large file transfers, use streaming.
5. **Consider Frameworks**: For complex applications, consider frameworks like Express or Koa.
* * *
## Summary
The `http` module of Node.js provides fundamental capabilities for building network applications. Although many higher-level frameworks are available today, understanding how the `http` module works remains crucial for any Node.js developer. By mastering this core module, you can better grasp how web applications operate and build custom solutions tailored to your needs.
[Node.js Built-in Modules](#)
YouTip