Search code examples
javascriptnode.jshttpparametersurl-routing

How to get URL Params with Node JS Http/Https module


I am programming the backend of my web application. And I'm doing the api and I need to be able to send data in the URLs. For example:

www.example.com/posts/123456789

Right now all I have is:

www.example.com/posts/?q=123456789

I would like to know if I could do something similar to what the express module does with the colon to declare params. But I want to do it with the node http module as I have already written all the routing with it and it would be a huge pain to move to express and have to memorize the functions for it.

if this isn't possible please let me know and I will have to stick to the query string.


Solution

  • Seems like HTTP module docs do not specify a way to do this, other than by using search params.

    In your case however, I think that the best course of action (if migrating to a framework like express is not an option) would be to manually deconstruct the URL with using something like: const urlSegments = request.url.split('/') and taking n-th segment (matching the route you specified).

    This is a bad solution in the long term, as it would be quite difficult to maintain, but it can get the job done if necessary.