javascriptnode.jsexpressmongooseurl-shortener

Node.js - How to create a request which can access the url before the root path "/'


I am trying to complete the freecodecamp project- url shortener in glitch.

glitch project link: https://glitch.com/edit/#!/url-sh0rtn3r

What i am able to do currently is:-

the shortened url for https://www.freecodecamp.com becomes https://url-sh0rtn3r.glitch.me/api/shorturl/9575 where 9575 points to the original url i.e. https://www.freecodecamp.com

Now i was wondering if i can somehow shorten the url further to be something like https://initialpart/api/shorturl/9575

But im stuck trying to figure out how to access the initialpart as a parameter inside a request where the path is pointing to whatever comes after initialpart.


Solution

  • You can get the "initialpart" (domain) from your request object with req.headers.host. In your case this would return "url-sh0rtn3r.glitch.me" as a string. You can then use that in your app however you like. You can also get the rest of the request URL path with req.url, which in the above example would return "/api/shorturl/9575" as a string.