Node http Module Tutorial
The Node.js HTTP module is a core module that allows you to create HTTP servers and clients.
In this tutorial, you will learn http module in node with examples.
Introduction to the HTTP Module
- The HTTP module in Node.js provides functionality to create HTTP servers and clients.
- It is commonly used to build web servers and make HTTP requests to other servers.
Creating an HTTP Server
- To create an HTTP server, you need to require the http module and use its createServer method.
- You must provide a callback function that will be called for each incoming request.
const http = require('http');
const server = http.createServer((req, res) => {
// Handle the request here
});
const port = 3000;
server.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
Handling HTTP Requests
- The req object represents the HTTP request and contains information about the client's request.
- You can access properties like req.url, req.method, and req.headers to examine the request.
Sending HTTP Responses
- The res object is used to send an HTTP response to the client.
- You can set response headers, status codes, and send a response body using methods like res.setHeader(), res.statusCode, and res.end().
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, world!\n');
});
Parsing Request Data
- To work with data sent in the request, you may need to parse it.
- Commonly used data formats include URL parameters and request bodies
const server = http.createServer((req, res) => {
// Parse URL parameters
const urlParams = new URL(req.url, `http://${req.headers.host}`);
const queryData = urlParams.searchParams.get('data');
// Read request body
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
console.log('URL Parameter:', queryData);
console.log('Request Body:', body);
res.end('Data received');
});
});
Making HTTP Requests as a Client
- The HTTP module can be used to make HTTP requests to other servers as a client.
- The http.get() and http.request() methods are commonly used to initiate requests.
const http = require('http');
const options = {
hostname: 'example.com',
path: '/api/data',
method: 'GET',
};
const req = http.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log(data);
});
});
req.end();