How to retrieve an URL from the route using #Param - javascript

I am writing an image processor proxy, similar to imageproxy, but using NestJS.
I want to declare an endpoint like this: GET /api/trim/http://your.image.url where http://your.image.url is the URL of the image that I want to transform.
In my controller, I would do something like this:
#Get('trim/:imageUrl')
async trimCanvas(
#Param('imageUrl') imageUrl: string,
): Promise<any> {
console.log(imageUrl);
return 'OK';
}
However, if I make a request, the controller is never hit and, instead, I get a default 404. Any ideas on how to make this work?

By default, slashes will not be captured by the url param. You can append a regex in parentheses to your route param to change this behavior. Add a wildcard * to your param, so that it also accepts /:
#Get('trim/:imageUrl(*)')
Try it out in this codesandbox.

Related

Arbitrary URL in Express URL parameters?

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?
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%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DucZl6vQ_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.
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.

Laravel resource route delete from axios

I would like to setup axios to delete a record using a resource route:
axios.delete('/job-management', this.deletedata).then((res)=>{
console.log(res);
})
For my routes I have:
Route::resource('job-management', "PositionsController", [ 'as' => 'jobs']);
Now, in my PositionsController I have:
public function destroy(Positions $positions) {
return $positions;
}
But the above always returns "method not allowed". How can I handle a delete request with the axios delete() method?
Laravel throws the MethodNotAllowedHttpException when we attempt to send a request to a route using an HTTP verb that the route doesn't support. In the case of this question, we see this error because the JavaScript code sends a DELETE request to a URL with the path of /job‑management, which is handled by a route that only supports GET and POST requests. We need to change the URL to the conventional format Laravel expects for resourceful controllers.
The error is confusing because it hides the fact that we're sending the request to the wrong URL. To understand why, let's take a look at the routes created by Route::resource() (from the documentation):
Verb URI Action Route Name
GET /job-management index job-management.index
GET /job-management/create create job-management.create
POST /job-management store job-management.store
GET /job-management/{position} show job-management.show
GET /job-management/{position}/edit edit job-management.edit
PUT/PATCH /job-management/{position} update job-management.update
DELETE /job-management/{position} destroy job-management.destroy
As shown above, URLs with a path component of /job-management are passed to the controller's index() and store() methods which don't handle DELETE requests. This is why we see the exception.
To perform a DELETE request as shown in the question, we need to send the request to a URL with a path like /job-management/{position}, where {position} is the ID of the position model we want to delete. The JavaScript code might look something like:
axios.delete('/job-management/5', this.deletedata).then((res) => { ... })
I've hardcoded the position ID into the URL to clearly illustrate the concept. However, we likely want to use a variable for the this ID:
let positionId = // get the position ID somehow
axios.delete(`/job-management/${positionId}`, this.deletedata).then((res) => { ... })
The URL in this form enables Laravel to route the DELETE request to the controller's destroy() method. The example above uses ES6 template string literals because the code in the question suggests that we're using a version of JavaScript that supports this feature. Note the placement of backticks (`) around the template string instead of standard quotation marks.
as I can see in your code above, you pass Positionseloquent as a parameter to destroy method but in your vueJS you don't pass this object. for that you would pass it like this :
axios.delete('/job-management/${id}').then((res)=>{
console.log(res);
})
and the id param inside the url of ur axios delete, it can object of data or any think.
i hope this help you

Passing a query string to a request as an actual string using Node and Express

So, basically what I am doing is scraping a webpage, getting all of the data I want and displaying it on a webpage on my site. When scraping this specific page i need the link within the 'href' tag. However, this particular site doesn't use regular links. Inside the 'href' tag is a query string. My plan was to take what was inside the 'href' and create a url to make my next request, but now when I try to pass the query string into the url, I can not access it in Node via req.params
I want to know if there is a way to maybe pass a query string without the server thinking it is a query string, or will I have to use req.query to take all the params and build the URL again from scratch?
Here are some examples of what I am talking about:
page1.ejs:
some.href = "?variable=bleh"
Server-side handling:
app.get('/display/:string', function(req, res) {
var url = "http://theurlineed.com/" + req.params.string;
});
This code does not work. When i click on the link it tells me it couldn't get /display/?variable=bleh
You need to encode the query string so that it is not treated like a query string in the URL:
some.href = encodeURIComponent("?variable=bleh");
So then your URL will be: /display/%3Fvariable%3Dbleh. As mentioned in the comments, Express will automatically decode the value in req.params.string so it will be the right value.

Node JS - Express.js get query with multiple parameters

I'm quite new to JavaScript and Node JS and I have a such a situation. When I try to call get of express.js with a single parameter everything works fine, but when I try to call get with more than one parameter, it trims the query.
For example I have such call and function
app.get('path/data', myFunc);
// in another file
function myFunc(req, res) {
// do some stuff
}
When the url is path/data?id=5 or path/data?name=foo everything is fine. But when I use for example url like path/data?id=5&name=foo in myFunc I get url as path/data?id=5. So I get url's first part - what is before & sign.
Now what am I doing wrong? Is there something that I'm missing? How can I get whole url in myFunc without being trimmed?
Use
app.get('path/data?:id?:name')
And for retrieving the values, use req.query.id and req.query.name.
For accessing the REST api, you need to hit:
http://localhost:8080/demo?id=3&name=stack
So, by this you can add multiple parameters in your api.
Hope this helps.
I found the problem. I was requesting via curl and it turns out that shell command trims in case of there is an & in the url. So there is a need no add quotes like this
curl "path/data?id=5&name=foo"

How to get url from parameter

One of my parameters in the routing is actually an url.
router.get('/api/sitemap/:url', function(req, res)
{
var url = req.params.url;
...
}
How do I allow this to go through when the :url is actually a link like "http://domain.com/file.xml".
I get a 404 error which I understand as it is not linking properly and cannot process as it errors.
Thanks in advance.
Your router returns 404 because it can't recognize the path.
You should either encode the url param as suggested in the comments, or slice it further, as:
.get('/api/site/:domain/: file', cb)
The trouble there is that if you also pass the protocol, you have to match even that.
Don't have a console to try now, but I think you might be able to pass a wildcard:
'/api/sitemap/*'
You would have to parse out the url on your own then, but it's simple:
var url = req.url.substr(14);
(Not sure if it's 13 or14 on the index there, counting on hands since I'm on my mobile :-)).

Categories