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:

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/

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?


You can use an expression to for your URL placeholders:

app.get('/new/:url(*)', (req, res) => {
  console.log(req.params.url) // will output ''

Answered By – hjpotter92

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published