To set up an HTTP server in Node.js, you can use the built-in http
module. Here’s a code example that demonstrates how to create a basic HTTP server:
const http = require('http');
// Define the port number for your server
const port = 3000;
// Create an HTTP server
const server = http.createServer((req, res) => {
// Set the response headers
res.writeHead(200, {'Content-Type': 'text/plain'});
// Send a response to the client
res.end('Hello, World!');
});
// Start the server and listen on the specified port
server.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
Explanation:
- The code starts by requiring the built-in
http
module, which provides functionality for creating HTTP servers and handling requests. - Next, you can define the port number where you want your server to listen for incoming requests. In the example, the server is set to listen on port 3000, but you can change it to any available port number.
- The
http.createServer()
function is used to create an HTTP server. It takes a callback function that will be invoked whenever a request is received. - Inside the callback function, you can handle the incoming request and prepare the response to send back to the client. In the example, we set the response headers using
res.writeHead()
with a status code of 200 (indicating a successful response) and a content type of'text/plain'
. - After setting the headers, you can use
res.end()
to send the response to the client. In this case, it sends the string'Hello, World!'
as the response body. - Finally, the
server.listen()
method is called to start the server and make it listen on the specified port. It also takes a callback function that will be executed once the server has started successfully. In the example, it logs a message to the console indicating that the server is listening on the specified port.
Make sure to choose an available port number and update const port = 3000;
accordingly. You can access your server by opening a web browser and navigating to http://localhost:3000
(assuming you’re running the server locally).