In this post, we will talk about creating a simple web server.
Creating a web server in Node
we use http module to create a server. For creating a server, we have the createServer method that accepts two parameters request and response.
If we console.log() the request, we can see values like headers, method (GET, POST, PUT, etc.), URL, statusCode, and there are many other things in the request.
end() method on response is used to send back a simple response.
We have stored the created server results in a server variable.
Now, we have used server.listen() to listen incoming requests. It will listen to requests on port 8000. listen method accepts three parameters and they are port, host and a callback function.
In the above image, you can see I have given 8000 as a port, you can give anything for your port, such as 3001, 9000, etc.
In the host, which is the present address of your computer. In this parameter you can write localhost or simply ‘127.0.0.1’ (localhost usually has this address. So, you can either write localhost or ‘127.0.0.1’).
The third parameter in the listen method is the callback function.
Now, when I run the above code in my VSCode, it will give this output (check the image below).
Please note: I used index.js file for writing the above code, so to run this code, I need to write node index.js