DEV Community

jesse-crypted
jesse-crypted

Posted on • Edited on

I created a web server πŸ‘¨β€πŸ’»

On day 2 of my 100 days of code in learning Node.js, I was able to learn ho to create a web server without using the express framework. So the web server was built by using the Nodejs HTTP module.
So let dive in the tutorial.
What is a web server and how come Node.js can do that: A web server can either be a software or hardware that responds to client (i.e browser, it is through a browser we access a web server) request. Web servers store or host websites, content on the internet and when users needed them they make a request to the server. The reason Node.js can do this is because with Node.js we can now run Javascript outside the browser.
So for us to build this server we use a module provided by Node.js called the http module, we initialise it when we start our code. We can save our code in a file called app.js
const http = require("http");

const http = require("http");

const server = http.createServer((req, res) => {
res.writeHead(200, {
'content-type': 'text/html'
})
  res.end("<h1>Hello from the server</h1>");
});

server.listen(8000, "127.0.0.1", () => {
  console.log("...listening to requests on port 8000");
});
Enter fullscreen mode Exit fullscreen mode

We can now run our web server using node app.js. Visit http://127.0.0.1:8000 and you will see a message saying "Hello from the server".
NOTE: this web server is however hosted on a localhost with an IP Address of 127.0.0.1 and on port 8000.
IP address are special adresses for computers on the internet.
Port numbers are like doors into a computer.
Yay we have finally created our web server πŸŽ‰πŸŽ‰πŸŽ‰πŸŽ‰πŸŽ‰πŸ˜‰

Top comments (0)