DEV Community

Paweł Partyka
Paweł Partyka

Posted on

Path parameters in node.js

Today we will create a route with path parameters. Fortunately, Cavia's parameter parsing mechanism is built-in and using it is very simple.

Step 1: New endpoint

Create a new endpoint with path params - to indicate the position of a parameter in the path, add a colon in front of the parameter name.

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

export const GuineaPigDetailsRoute: Route = {
  handler: async (request, response): Promise<void> => {
    const id = request.params.id; // 👈

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

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

Step 2: Make request

Make a request to newly created endpoint.

curl -XGET 'http://localhost:8080/guinea-pigs/details/1245'
Enter fullscreen mode Exit fullscreen mode

Yes, it's that simple.
See you!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

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