Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with slash characters in request parameter using Express route

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?

like image 377
BenShelton Avatar asked Feb 20 '17 18:02

BenShelton


1 Answers

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'
like image 62
hjpotter92 Avatar answered Sep 21 '22 20:09

hjpotter92