How can you create Http Server in Nodejs? Why you need it?
In Node.js, you can create an HTTP server using the built-in http module. Here’s an example code to create a basic HTTP server:
const http = require('http');const server = http.createServer((req, res) => { // set response header res.writeHead(200, { 'Content-Type': 'text/plain' }); // write response message res.write('Hello World!'); // end the response res.end();});// listen on port 3000server.listen(3000, () => { console.log('Server started on port 3000');});
const http = require('http');
const server = http.createServer((req, res) => {
// set response header
res.writeHead(200, { 'Content-Type': 'text/plain' });
// write response message
res.write('Hello World!');
// end the response
res.end();
});
// listen on port 3000
server.listen(3000, () => {
console.log('Server started on port 3000');
In the above code, http.createServer() method creates a new instance of http.Server. It takes a callback function with two arguments - req and res. The req object represents the client request and the res object represents the server response.
Inside the callback function, we set the response header using res.writeHead() method and write the response message using res.write() method. Finally, we end the response using res.end() method.
To start the server, we use the listen() method of the http.Server object. It takes two arguments - the port number to listen on and a callback function that is executed when the server is ready to accept requests.
You can use the HTTP module.
Using this module there’s a createServer function that turns your localmachine into a HTTP server.
createServer
See the sample code below.
/** * Node.js has a builtin HTTP module which gives us * the ability to transfer over HTTP. */const http = require("http");/*Let's create a simple web server*/http.createServer((request, response) => { response.write("Hello Web Sever"); response.end();}).listen(9090);
/**
* Node.js has a builtin HTTP module which gives us
* the ability to transfer over HTTP.
*/
const http = require("http");
/*Let's create a simple web server*/
http.createServer((request, response) => {
response.write("Hello Web Sever");
response.end();
}).listen(9090);