Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use query parameters in Nest.js?

I am a freshman in Nest.js.

And my code as below

  @Get('findByFilter/:params')   async findByFilter(@Query() query): Promise<Article[]> {    } 

I have used postman to test this router

http://localhost:3000/article/findByFilter/bug?google=1&baidu=2

Actually, I can get the query result { google: '1', baidu: '2' }. But I'm not clear why the url has a string 'bug'?

If I delete that word just like

http://localhost:3000/article/findByFilter?google=1&baidu=2

then the postman will shows statusCode 404.

Actually, I don't need the word bug, how to custom the router to realize my destination just like http://localhost:3000/article/findByFilter?google=1&baidu=2

Here's another question is how to make mutiple router point to one method?

like image 640
Eve-Sama Avatar asked Mar 02 '19 11:03

Eve-Sama


People also ask

How do I get parameters in NestJS?

To get all query parameter values from a GET request, you can use the @Query() decorator function from the @nestjs/common module inside the parameter brackets of the controller's respective method in Nestjs.

How do you query parameters in a URL?

Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.

Is NestJS better than express?

Another use case can be enterprise-level web applications and ecommerce applications. NestJS is better suited for these as it is scalable, well-structured, and great for building large web applications. For building fintech and streaming applications, ExpressJS is better suited.

What is DTO in NestJS?

A DTO is an object that defines how the data will be sent over the network. We could determine the DTO schema by using TypeScript interfaces, or by simple classes. Interestingly, we recommend using classes here.


1 Answers

Query parameters

You have to remove :params for it to work as expected:

@Get('findByFilter') async findByFilter(@Query() query): Promise<Article[]> {   // ... } 

Path parameters

The :param syntax is for path parameters and matches any string on a path:

@Get('products/:id') getProduct(@Param('id') id) { 

matches the routes

localhost:3000/products/1 localhost:3000/products/2abc // ... 

Route wildcards

To match multiple endpoints to the same method you can use route wildcards:

@Get('other|te*st') 

will match

localhost:3000/other localhost:3000/test localhost:3000/te123st // ... 
like image 73
Kim Kern Avatar answered Sep 21 '22 04:09

Kim Kern