To create a simple HTTP server in Node.js, you’ll need to use the built-in ‘http‘ module. Here’s a step-by-step guide on how to create a basic server:
1. Start by importing the ‘http‘ module by requiring it:
const http = require('http');
2. Next, define a hostname and port number for the server:
const hostname = '127.0.0.1'; // localhost
const port = 3000;
3. Now, create the server using the ‘http.createServer()‘ method. This method takes a callback function with two arguments: ‘request‘ and ‘response‘. Inside the callback function, you can set the response status code, headers and the response body:
const server = http.createServer((request, response) => {
response.statusCode = 200; // The status code for a successful HTTP request
response.setHeader('Content-Type', 'text/plain');
response.end('Hello, World!n');
});
4. Finally, start the server by invoking the ‘listen()‘ method on the ‘server‘ object, and pass the port and hostname you’ve defined:
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Here’s the complete code:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((request, response) => {
response.statusCode = 200;
response.setHeader('Content-Type', 'text/plain');
response.end('Hello, World!n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
To run the server, save your code in a file called ‘server.js‘ and then execute the following command in your terminal:
node server.js
This will start the server, and it will be accessible at ‘http://127.0.0.1:3000‘. When you visit this URL with your web browser or make an HTTP request to it, you’ll receive a plain-text response with the content "Hello, World!"