'How can I route a path which has '?' character in it in nestjs?
For example in browser we send /controller/test?value=2 but I want to route this at an endpoint? I have another endpoint /controller/test which captures even the requests made to this route
Solution 1:[1]
That's a query string.
You can use @Query
decorator in the function parameter
@Get('/path')
async find(@Query() query) {
console.log(query);
}
Solution 2:[2]
In this situation, it seems like your route /controller/test
accepts a query parameter value
. Regardless of whether or not you query that route with the query parameter value
, all requests will hit your route controller at controller/test
.
In other words, your server treats
GET /controller/test
as a request to /controller/test
as a request with value: undefined
and
GET /controller/test?value=2
as a request to /controller/test
as a request with value: 2
Therefore, your controller should look something like (assuming you're using typescript)
interface ControllerQuery {
value?: number
}
@Get('/controller/path')
async controller( @Query query: ControllerQuery ) {
if (query.value) {
console.log(query.value);
} else {
console.log('No value provided, now what?');
}
}
Solution 3:[3]
Like said above, query params are not filtered by route. But you could do something like this, which would be more restful as well. That or having a search
endpoint.
@Get('/path')
async without() {
console.log('without param');
}
@Get('/path/:value')
async find(@Param('value') value: string,) {
console.log(value);
}
@Get('/path/search')
async search(@Query() query) {
console.log(query);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | n1md7 |
Solution 2 | |
Solution 3 | moogs |