Home > Software design >  How can I route a path which has '?' character in it in nestjs?
How can I route a path which has '?' character in it in nestjs?

Time:05-10

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

CodePudding user response:

That's a query string.

You can use @Query decorator in the function parameter

@Get('/path')
async find(@Query() query) {
  console.log(query);
}

More info

CodePudding user response:

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?');
    }
  }
  • Related