Michael
Michael

Reputation: 177

URL as parameter in Express

Using Node.js with Express, how do I accept a URL as a parameter?

i.e http://example.com/site/http%3A%2F%2Fgoogle.com

I have the following handler

app.get('/site/:dest', function (req, res, next) {
   res.end('URL = ' + req.params.dest);
});

Rather than getting the expected response i get a 404:

The requested URL /site/http://www.google.com was not found on this server.

If i request example.com/site/hello it works fine, but not for passing a URL. I assume its the forward slashes escaping that's causing the problem.

Is there a correct way to do this?

Upvotes: 1

Views: 3260

Answers (3)

lee
lee

Reputation: 161

It's worked for me

app.get('/site/*', function (req, res, next) {
  res.end('URL = ' + req.params[0]);
});

Upvotes: 3

Michael
Michael

Reputation: 177

Here is a workaround:

Changed the routing and now using req.query

app.get('/', function (req, res, next) {
   res.end('URL = ' + req.query['site']);
});

Now, http://example.com/?site=http%3A%2F%2Fexample.com%2F%3Fhello%3Dworld%26foo%3Dbar works as expected.

Upvotes: 1

sheplu
sheplu

Reputation: 2975

You need to encode your parameter's URL. You will have a lot of issues if you just send the URL as a param.

Best way is to url encode the param and on your nodejs side you will need to url decode

Example: https://www.google.com will be https%3A%2F%2Fwww.google.com

Upvotes: 1

Related Questions