The HTTP module is an internal module of Node.js that allows developers to work with the HTTP protocol. With the HTTP module, you can create HTTP servers that handle incoming requests and return responses based on those requests. In addition, you can also use the HTTP module to send HTTP requests to other servers and APIs.
The HTTP module provides a range of features, including handling request and response headers, reading and writing request and response bodies, and handling HTTP status codes. With the HTTP module, you can also perform tasks such as sending cookies, handling redirects, and working with HTTPS connections.
Creating server
You can create an HTTP server using the createServer() method. The createServer() method takes a callback function that is executed whenever a new HTTP request is received. The callback function receives request and response objects. In the callback function, you can handle the incoming request and return a response.
Using the listen() method, you can set up the HTTP server to listen to a specific port. The listen() method takes the port number and an optional callback function that is executed once the server is ready to accept requests.
Here are a few steps to get started with the module:
- The first step is to access the HTTP module in our Node.js application using the require() function;
- Once you have required the HTTP module, you can create an HTTP server using the
http.createServer()method; - Then call
server.listen()method to start the server.
// Access HTTP module using the require() function
const http = require('node:http');
// Create an HTTP server
const server = http.createServer((request, response) => {
console.log('Connected successfully');
});
// Start the server
server.listen(8080);
This code snippet allows you to see the message Connected successfully in the console when you open http://localhost:8080 on your browser. It means that the server was created and it is listening to incoming requests. But did you notice that the website is loading and you haven't received any response from the server? This is because you haven't returned any information and have not closed the connection either.
Here is a more advanced example, which allows you to send something back to the browser:
const http = require('node:http');
const server = http.createServer((request, response) => {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write('Hello from HTTP server');
response.end();
});
server.listen(8080, () => {
console.log('Server running on port 8080');
});
The snippet given above sends the message Hello from HTTP server. There is also an HTTP header for the response. And it has an added console message which informs you that the server is running and listening to requests. You can check it by reloading the browser page on the same host and port.
Making a request
Apart from creating servers, you can also use the HTTP module to make HTTP requests to other servers and APIs. You can make HTTP requests using the get() method. The get() method takes two arguments: the URL of the resource you want to request and a callback function that is executed once the server receives the response. In the callback function, you can handle the response and read the response data.
Here is the simplest way to use http.get():
const http = require('node:http');
http.get('http://jsonplaceholder.typicode.com/todos/1');
When you run this snippet a request is sent but nothing will happen. If there is a mistake with the request, it will be dropped with an error. For example, try to change typicode to typacode, and you will see that request will be made to a non-existent address. Hence it returns an error. To get something back as a response, you need to expand and make the code more complex.
const http = require('node:http');
http.get('http://jsonplaceholder.typicode.com/todos/1', (response) => {
response.on('data', (data) => {
console.log(data.toString());
});
});
Using the get() method, you can read the server response status and other information. The code snippet shown above will give the following answer as a string:
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
Try it, and see the output.
Conclusion
The Node.js HTTP module is a tool that allows developers to create web servers and make HTTP requests. With the HTTP module, you can handle incoming requests and return responses, as well as make requests to other servers and APIs. By mastering the HTTP module, developers can build fast, efficient, and scalable server-side applications with Node.js.