Say I have an express get function:
app.get("/api/processing/:type/:link/", () => { ... })
where :link
is meant to be an arbitrary, full URL such as https://www.youtube.com/watch?v=ucZl6vQ_8Uo
and :type
can be one of a few values.
The problem is that whenever I try to use it, I get something like this:
Cannot GET /api/processing/audio/https://www.youtube.com/watch
How can I make sure that the URL is passed as a parameter instead of treated like part of the path?
CodePudding user response:
If you want a full URL to be treated as a single path segment in your URL to match your app.get("/api/processing/:type/:link/", ...)
route definition, then you have to encode it properly on the client side so that it actually contains no URL part separators in the encoded piece and thus will match your Express route definition.
You can use encodeURIComponent()
for that as in:
const targetURL = 'https://www.youtube.com/watch?v=ucZl6vQ_8Uo';
const requestURL = `https://yourdomain.com/api/audio/${encodeURIComponent(targetURL)}`;
// send your request to requestURL
Then, make the http request to requestURL. Express will handle decoding it properly for you on the server-end of things.
This will generate a requestURL that looks like this:
"https://yourdomain.com/api/audio/https://www.youtube.com/watch?v=ucZl6vQ_8Uo"
and you can see in that URL that there are no path separators or query separators, allowing Express to match it properly against your Express route delcaration. You will see that the /
, :
and ?
characters are all escaped so when Express parses the URL into its parts, this whole URL is treated as a single path segment that will match your :link
in the route definition.
CodePudding user response:
You can encode the URL so it can be passed as a parameter:
app.get("/api/processing/:type/", (req, res) => {
const link = encodeURIComponent(req.query.link);
// your processing logic here
});
In this example, link is passed as a query parameter rather than part of the path, so you can use req.query.link to access it. When making the request, you would pass the link in the format /api/processing/audio/?link=https://www.youtube.com/watch?v=ucZl6vQ_8Uo.