Create a simple http server with node.js

pawpartyka

Paweł Partyka

Posted on November 23, 2023

Create a simple http server with node.js

Welcome to my new blog! Today we will start the adventure of exploring the world of web applications using Node.js. We'll start with something simple - create your own HTTP endpoint using Cavia Framework.

Why Cavia?

Cavia is a lightweight library for handling HTTP requests in Node.js. Its simplicity makes it perfect for those who want to quickly start creating simple web applications.

Step 1: Installation

The first step is to install the packages for your project using the command below.

npm install @caviajs/http-router @caviajs/http-exception rxjs --save
Enter fullscreen mode Exit fullscreen mode

You can also use a template available at typescript-starter.

Step 2: Endpoint

Now let's create our entry point. Let's enter the following code in the app/web.ts file:

import http from 'http';
import { HttpRouter } from '@caviajs/http-router';

(async () => {
  const httpRouter: HttpRouter = new HttpRouter();

  httpRouter
    .route({
      handler: async (request, response): Promise<string> => {
        return 'Hello world!';
      },
      method: 'GET',
      path: '/hello',
    });

  const httpServer: http.Server = http.createServer((req, res) => {
    httpRouter.handle(req, res);
  });

  httpServer.listen(8080, () => {
    console.log(`Http server listening at port ${8080}`);
  });
})();
Enter fullscreen mode Exit fullscreen mode

Step 3: Starting the server

When our entry point is ready, we can now start the server.

npx ts-node app/web.ts
Enter fullscreen mode Exit fullscreen mode

Running the app/web.ts file will start the server and we will be able to test our endpoint by entering the address in the browser http://localhost:8080/hello.

It's all for today! I hope this short post was helpful to you. In the next articles we will develop our web application. See you!

💖 💪 🙅 🚩
pawpartyka
Paweł Partyka

Posted on November 23, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related