How to Use HTTP Module in Node.js: Simple Guide
In Node.js, you use the
http module to create a web server that listens for requests and sends responses. You start by importing http, then use http.createServer() to define how to handle requests, and finally call server.listen() to start the server.Syntax
The http module provides the createServer() method to create a server. This method takes a callback function with request and response objects. You use response.write() to send data and response.end() to finish the response. Finally, server.listen(port) starts the server on a specified port.
javascript
const http = require('http'); const server = http.createServer((request, response) => { // Handle incoming requests response.write('Hello World'); response.end(); }); server.listen(3000);
Example
This example creates a simple server that responds with 'Hello World' to every request. It listens on port 3000. When you visit http://localhost:3000 in your browser, you will see the message.
javascript
const http = require('http'); const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.write('Hello World'); res.end(); }); server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); });
Output
Server running at http://localhost:3000/
Common Pitfalls
- Forgetting to call
response.end()causes the client to wait forever. - Not setting the
Content-Typeheader can make browsers misinterpret the response. - Using
require('http')is necessary; forgetting it causes errors. - Trying to listen on a port already in use will throw an error.
javascript
/* Wrong: Missing response.end() */ const http = require('http'); const server = http.createServer((req, res) => { res.write('Hello'); // res.end() missing here }); server.listen(3000); /* Right: Include response.end() */ const server2 = http.createServer((req, res) => { res.write('Hello'); res.end(); }); server2.listen(3001);
Quick Reference
Remember these key methods and properties when using the http module:
| Method/Property | Description |
|---|---|
| http.createServer(callback) | Creates a new HTTP server with a request handler |
| server.listen(port) | Starts the server listening on the given port |
| response.write(data) | Sends data to the client |
| response.end() | Ends the response, signaling completion |
| response.setHeader(name, value) | Sets HTTP headers for the response |
| request.url | The URL path requested by the client |
| request.method | The HTTP method used (GET, POST, etc.) |
Key Takeaways
Use
http.createServer() with a callback to handle requests and responses.Always call
response.end() to complete the response and avoid hanging connections.Set appropriate headers like
Content-Type to inform the client about the response data.Start the server with
server.listen(port) to listen for incoming requests.Check for port conflicts and handle errors when starting the server.