1

I have this route /new/:url. Now, when I make request like /new/https://www.google.com, I get Cannot GET /new/https://www.google.com as the response. What I expect is to get the string https://www.google.com. I read this answer URL component encoding in Node.js about encoding the URL but how will I be able to do so when a GET request is made to the route /new/:url ? Here is my code for that route

app.get('/new/:url',(req,res) => {
  const url = encodeURIComponent(req.params.url);
  console.log(url);
  res.json({
    url
  });
});
Zameer Haque
  • 394
  • 4
  • 24

2 Answers2

3

You can make a try this way with wildcard routing, not tested but it should work

app.get('/new/*',(req,res) => {
  const url_param = req.params[0];
  const url = req.hostname;
  console.log(url,url_param);
  res.json({
    url
  });
});

req.params[0] will give you the https://www.google.com portion of http://www.yourapp.com/new/https://www.google.com and req.hostname will give you the original http://www.yourapp.com/ .

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
  • This works. But I don't understand why my route handler does not works ? This method also does not encode the URL then why it is not treating the `/` in `https://www.google.com` as seperate parts of url and breaking the response. – Zameer Haque Aug 06 '17 at 06:23
  • This may work but every parameter should be encoded while transporting as url component. – wartoshika Aug 06 '17 at 06:24
0

You have to route to an encoded url. In your router callback function you should decode the url component.

app.get('/new/:url',(req,res) => {
   const url = decodeURIComponent(req.params.url);
   console.log(url);
   res.json({
     url
   });
 });

And the part where you link to this /new section should encodeURIComponent() the passed url.

The encoded url should look like /new/http%3A%2F%2Fgoogle.de

Frontend Part:

const baseUrl = '/new';
const urlParameter = 'http://example.com';
const targetUrl = `${baseUrl}/${encodeUriComponent(urlParameter)}`;
const method = 'GET';

const xhr = new XMLHttpRequest();
xhr.open(method,targetUrl);
xhr.onload = () => {

    const jsonCallback = JSON.parse(xhr.response);
}

xhr.send();
wartoshika
  • 531
  • 3
  • 10
  • Do you use a frontend framework? Since the backend lib is express (i think) the frontend should do the work. Ill edit my answer to provide a non framework example. – wartoshika Aug 06 '17 at 06:17