DEV Community

Paweł Partyka
Paweł Partyka

Posted on

Query parameters in node.js

Today we will use Cavia to parse the request query parameters.

Step 1: Installation

First, let's install the @caviajs/http-query package.

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

Step 2: Usage

Now, use the HttpQuery in route handler to parse query parameters.

import { Route } from '@caviajs/http-router';
import { HttpQuery } from '@caviajs/http-query'; // 👈

export const GuineaPigListRoute: Route = {
  handler: async (request, response): Promise<void> => {
    const query = HttpQuery.parse(request); // 👈

    console.log(query); // 👈 do sth with query parameters...
  },
  method: 'GET',
  path: '/guinea-pigs/list',
};
Enter fullscreen mode Exit fullscreen mode

Remember to add the newly created route to the HttpRouter instance and start the server.

Step 3: Make request

Make a request to newly created endpoint.

curl -XGET 'http://localhost:8080/guinea-pigs/list?name=foo'
Enter fullscreen mode Exit fullscreen mode

Yes, it's that simple.
See you!

Top comments (0)