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!

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

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

Okay