Abdelaziz Mokhnache
Abdelaziz Mokhnache

Reputation: 4349

how to pass a url as a "url parameter" in express?

In my express app I have a router listening to api/shorten/:

    router.get('api/shorten/:longUrl', function(req, res, next) {
        console.log(req.params.longUrl);
    }

When I use something like:

http://localhost:3000/api/shorten/www.udemy.com

I get www.udemy.com which is what I expect.

But when I use:

http://localhost:3000/api/shorten/http://www.udemy.com

I get a 404 error.

I want to get http://www.udemy.com when I access req.params.parameter.

Upvotes: 4

Views: 6755

Answers (4)

fullmoon6661
fullmoon6661

Reputation: 101

I just want to add that if you pass another params like ?param=some_param into your "url paramter" it will not show up in req.params[0]. Instead you can just use req.url property.

Upvotes: 0

Allan of Sydney
Allan of Sydney

Reputation: 1600

I'm not sure if you're still looking for a solution to this problem. Perhaps just in case someone else is trying to figure out the same thing, this is a simple solution to your problem:

app.get('/new/*', function(req, res) {

  // Grab params that are attached on the end of the /new/ route
  var url = req.params[0];

This way you don't have to sweat about any forward slashes being mistaken for routes or directories, it will grab everything after /new/.

Upvotes: 22

Omri Luzon
Omri Luzon

Reputation: 4214

You need to use encodeURIComponent in the client, and decodeURIComponent in the express server, this will encode all the not allowed characters from the url parameter like : and /

Upvotes: 2

Joshua J Wilborn
Joshua J Wilborn

Reputation: 526

You need to escape as so:

escape("http://www.google.com")

Which returns:

"http%3A//www.google.com"

Upvotes: 0

Related Questions