Welcome to our comprehensive guide on the Node.js HTTP module! In this lesson, we'll dive deep into creating and handling HTTP servers, making requests, and understanding response codes. Let's get started!
The HTTP (Hypertext Transfer Protocol) module in Node.js allows you to create web servers and make HTTP requests. It's an essential tool for building network applications, including web applications and APIs.
To create an HTTP server, you'll need to use the http module. First, let's install it:
npm install httpNow, let's create a simple server:
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!');
});
server.listen(3000, '127.0.0.1', () => {
console.log('Server running at http://127.0.0.1:3000/');
});In this example, we create a server, define a function to handle incoming requests, set the response status code and content type, and send a simple response. The server listens on port 3000 and IP address 127.0.0.1 (localhost).
Making HTTP requests is as easy as creating servers. Here's an example of making a GET request to Google's homepage:
const http = require('http');
const request = http.request('http://www.google.com', (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log(data);
});
});
request.on('error', (err) => {
console.error(err);
});
request.end();In this example, we create an HTTP request, handle the response data, and print it to the console.
Response codes are essential for understanding the status of an HTTP request. Here are some common response codes:
What is the purpose of the HTTP module in Node.js?
In this lesson, we've covered the basics of the Node.js HTTP module, including creating servers, making requests, and understanding response codes. With these skills, you're well on your way to building powerful web applications and APIs with Node.js!
Stay tuned for more in-depth lessons on Node.js and other exciting topics! 🚀
Remember to practice and experiment with the code examples provided. Happy coding! 😊