Home > OS >  Nest.js route param is not returning anything
Nest.js route param is not returning anything

Time:03-03

I am starting to learn Nest.js. Now I am trying to understand how route param works.

I have a controller with the following code.

import {Controller, Get, Param, Req, Res} from '@nestjs/common';
import { AppService } from './app.service';
import {Request, Response} from "express";

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get(':name')
  getHello(@Param('name') name: string,
           @Req() req: Request,
           @Res() res: Response): string {
    return name;
  }
}

As you can see in the code, I am trying to retrieve the name parameter. But when I go to this URL in the browser, http://localhost:3000/?name=test, I am getting the following error.

http://localhost:3000/?name=test

When I go to this URL instead, http://localhost:3000/test, it just keeps loading the page. What is wrong with my code and how can I fix it?

CodePudding user response:

There are 2 types of params decorators.

  • Route Param @Param('name') param: string on client you use http://localhost:3000/:name You will get name as string

using postman http://localhost:3000/john

  @Get(':name')
  getHello(@Param('name') name: string,
           @Req() req: Request,
           @Res() res: Response): string {
    return name;
  }
  • Query Params @Query() query: {[key: string]: string} on client you use http://localhost:3000/?name=test&age=40 the object you get is {name: "test", age: "40"}

example using both

 @Get(':name')
  getHello(@Param('name') name: string,
           @Query() query: {age: string}
           @Req() req: Request,
           @Res() res: Response): string {
    return name;
  }

using postman localhost:3000/john?age=30 You can access age from the @Query and name from @Param

also note that using numbers if @Query will always be parsed as a string if you are not using a Request DTO

  • Related