DEV Community

Paweł Partyka
Paweł Partyka

Posted on

Parse request body with node.js

In the last post we used the Cavia to create the first endpoint, today we will use this micro framework to parse the request body.

Step 1: Installation

First, let's install the @caviajs/http-body package, which enables parsing.

npm install @caviajs/http-body --save
Enter fullscreen mode Exit fullscreen mode

Step 2: New endpoint

Create a new endpoint whose method is POST, PUT or PATCH.

import { Route } from '@caviajs/http-router';
import { HttpBody } from '@caviajs/http-body'; // 👈

export const GuineaPigCreateRoute: Route = {
  handler: async (request, response): Promise<void> => {
    const body = await HttpBody.parse(request, 'json'); // 👈

    console.log(body);
  },
  method: 'POST', // 👈
  path: '/guinea-pigs',
};
Enter fullscreen mode Exit fullscreen mode

The created endpoint add to HttpRouter instance.

import http from 'http';
import { HttpRouter } from '@caviajs/http-router';
import { GuineaPigCreateRoute } from './routes/guinea-pig-create-route'; // 👈

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

  httpRouter
    .route(GuineaPigCreateRoute); // 👈

  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: Start server

Start the server using the terminal.

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

Step 4: Make request

Make a request to our newly created endpoint.

curl -XPOST -H "Content-type: application/json" -d '{"name":"Hello World"}' 'http://localhost:8080/guinea-pigs'
Enter fullscreen mode Exit fullscreen mode

It's all for today! I hope this short post was helpful to you.
See you!

Top comments (0)