I'm trying to replace our current backend service using Nestjs library, however, I want to create a route with 2 optional parameters in the URL something like :
/route/:param1/config/:OptionalParam3?/:OptionalParam3?
that means the route should catch :
route/aa/config
route/aa/config/bb
route/aa/config/bb/cc
how can I achieve that, I have tried to use ?
and ()
but it's not working well.
Adding Optional Parameters to your Order Page URLs To add a third parameter, add another ampersand & , then the name of the parameter, and then the value for the parameter.
To get the URL parameter values or params from a GET request, we can use the @Param decorator function from the @nestjs/common module before the Controller method in Nestjs.
Redirection. To redirect a response to a specific URL, you can either use a @Redirect() decorator or a library-specific response object (and call res.redirect() directly). @Redirect() takes two arguments, url and statusCode , both are optional. The default value of statusCode is 302 ( Found ) if omitted.
Router params name should be unique. The correct route path is:
Existing one is:
/route/:param1/config/:OptionalParam3?/:OptionalParam3?
Correction:
/route/:param1/config/:OptionalParam3?/:OptionalParam4?
Opinion: You can use query params if the params are optional. It is never a good idea to create optional param routes (disagreements agreed). Both serve the same purpose, but having them as the query params makes it more understandable for debugging and fellow developers.
If you are looking for how to annotate an optional query parameter, you can do it like so:
@ApiQuery({
name: "myParam",
type: String,
description: "A parameter. Optional",
required: false
})
async myEndpoint(
@Query("myParam") myParam?: string
): Promise<blah> {
[...]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With