To create an HTTP server in Node.js, you can use the built-in http
module. Here's a simple example:
const http = require('http');
// Create the server
const server = http.createServer((request, response) => {
// Set the response header
response.setHeader('Content-Type', 'text/plain');
// Set the response content
response.write('Hello, World!');
// End the response
response.end();
});
// Start the server
server.listen(3000, 'localhost', () => {
console.log('Server is running on http://localhost:3000');
});
In the above example, we use the createServer
method of the http
module to create an HTTP server. It takes a callback function that will be called whenever a request is received. The callback function takes two parameters: request
represents the incoming request, and response
represents the outgoing response.
Inside the callback function, you can set the response headers using the setHeader
method of the response
object. In this example, we set the Content-Type
header to text/plain
.
You can send the response content using the write
method of the response
object. In this case, we simply send the string "Hello, World!".
Finally, we end the response using the end
method of the response
object.
To start the server, we call the listen
method on the server object. It takes the port number and the hostname (optional) as arguments. In this example, the server listens on port 3000 of the localhost. The callback function passed to listen
is called once the server starts, and we log a message to indicate that the server is running.
You can run this code using Node.js, and it will create an HTTP server that listens on http://localhost:3000
and responds with "Hello, World!" for every request it receives.
Comments
Post a Comment