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!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay