10

I'm currently working on a URL shortener app using Express. I want the user to be able to enter a URL like this:

https://www.exampleurlshortener.com/new/https://www.google.com

The problem is whenever I try to specify the parameter using Express it will only extract the 'https:' section and everything after that is lost because the 2 backslashes are registering as a new route:

app.get('/new/:url', (req, res) => {
  console.log(req.params.url) // outputs 'https:'

I thought about specifying each section as a new parameter but if inner is blank this ends up throwing a 404. I would need to check if inner is blank using this method otherwise the user would be able to type https:/something/www.google.com

app.get('/new/:prot/:inner/:address', (req, res) => {
  // throws 404 on valid addresses

Is there a simple way to solve this that I'm missing? Is the full URL available to be checked somewhere in the request? Or can parameters ignore backslashes?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
BenShelton
  • 901
  • 1
  • 8
  • 20
  • 2
    Try using `req.url`, or passing the parameter through query-string (I would recommend this 2nd approach, it will also be simpler for clients of your API) – salezica Feb 20 '17 at 18:27

2 Answers2

21

You can use an expression to for your URL placeholders:

app.get('/new/:url(*)', (req, res) => {
  console.log(req.params.url) // will output 'https://www.google.com'
Mitch Talmadge
  • 4,638
  • 3
  • 26
  • 44
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
0

SOLUTION

If any parameter contains "/", then add "(*)" after the parameter name.

EXAMPLE

Route: "/change/job-entry/:order_number"

The parameter "order_number" represents a value like "Anik-13/3/2023-Paharika-Srilanka"

CHANGES

Route: "/change/job-entry/:order_number(*)"