DEV Community

Halil Can Ozcelik
Halil Can Ozcelik

Posted on • Edited on

Building a web server with pure Node.js

There are many frameworks for Node.js to build a web server application. I am adding several of the most well-known ones below.

However, what if we don’t want to use any of them? We can build a web server by using pure Node.js. Of course, these frameworks make our life easier. Personally, I often use Express framework mostly but I will use pure Node.js API from now on as much as possible, especially for small projects :) This is simply because of the fact that these frameworks add many dependencies to our project so it causes huge node_modules.

node_modules becomes really huge in projects if you use many frameworks and libraries<br>
A simple web application or server can be built equally easily by using built-in modules making our apps more lightweight and easy to manage/maintain.
If you are used to reading code better than words, here’s a simple web server application built without any frameworks on Node.js. You can also check on GitHub from this link.

const http = require('http');
/** handle GET request */
function getHandler(req, res, reqUrl) {
  res.writeHead(200);
  res.write('GET parameters: ' + reqUrl.searchParams);
  res.end();
}

/** handle POST request */
function postHandler(req, res, reqUrl) {
  req.setEncoding('utf8');
  req.on('data', (chunk) => {
    res.writeHead(200);
    res.write('POST parameters: ' + chunk);
    res.end();
  });
}

/** if there is no related function which handles the request, then show error message */
function noResponse(req, res) {
  res.writeHead(404);
  res.write('Sorry, but we have no response..\n');
  res.end();
}

http.createServer((req, res) => {
  // create an object for all redirection options
  const router = {
    'GET/retrieve-data': getHandler,
    'POST/send-data': postHandler,
    'default': noResponse
  };
  // parse the url by using WHATWG URL API
  let reqUrl = new URL(req.url, 'http://127.0.0.1/');
  // find the related function by searching "method + pathname" and run it
  let redirectedFunc = router[req.method + reqUrl.pathname] || router['default'];
  redirectedFunc(req, res, reqUrl);
}).listen(8080, () => {
  console.log('Server is running at http://127.0.0.1:8080/');
});
Enter fullscreen mode Exit fullscreen mode

Firstly, I am creating an HTTP server by using createServer() method from the HTTP API of Node.js. In the request listener part of it, I am detecting the request and redirecting the related function.

As you can see, I have three functions which are getHandler(), postHandler() and noResponse(). They are handling the related URL request. URL and function couples are stored in router object as { method/url: function }.

Then, I parse the URL by using the WHATWG URL API. One of the reasons for this, I can get many URL functionalities such as pathname, host, origin, etc and I can handle easily without struggling string manipulations. After that, I construct my request key which is req.method + reqUrl.pathname for searching related function.

And finally, find the related function from router and call it by passing request and response objects. If there is no related function in the object then I call the default one which is noResponse() in our case.

Here is my approach to creating a simple web server with pure Node.js. In my opinion, working on a software language without any framework is also important to understand the basics of it.

You can read this MDN documentation for an extended example of a pure Node.js server. And of course, Node.js API is the most important document which helps you!

Additionally, you can check the server-side of my NLP Command Line App project for a more detailed implementation of the pure Node.js server. Also, read my article about this project if you want to learn more about it.

My some other articles:
Create a Multi-Language Website with React Context API
Chrome Devtool Tips
An NLP Command Line Application with Node.js

Top comments (2)

Collapse
 
wellingtonmacena profile image
Wellington Macena

postHandler method is not working. I had to remove on event to make it work. Are there problems to keep the code without it?

Collapse
 
halilcanozcelik profile image
Halil Can Ozcelik • Edited

Hi, it seems working fine, here is the ss:
ss