Reputation: 414
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
});
});
Upvotes: 1
Views: 1400
Reputation: 541
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();
Upvotes: 0
Reputation: 38552
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/ .
Upvotes: 3