Reputation: 1276
I'm trying to create a controller action in NestJS accessible via GET HTTP request which receives two params but they are undefined for some reason.
How to fix it?
@Get('/login')
login(@Param() params: LoginUserDto) {
console.log(params)
return 'OK'
}
import { ApiModelProperty } from '@nestjs/swagger';
export class LoginUserDto {
@ApiModelProperty()
readonly userName: string;
@ApiModelProperty()
readonly password: string;
}
Upvotes: 16
Views: 47525
Reputation: 4725
In Browser
localhost:3001/Products/v1/user2
Controller like this:
@Controller('Products')
export class CrashesController {
constructor(private readonly crashesService: CrashesService) { }
@Get('/:version/:user')
async findVersionUser(@Param('version') version: string, @Param('user') user: string): Promise<Crash[]> {
return this.crashesService.findVersionUser(version, user);
}
}
Upvotes: 29
Reputation: 73
Right now I am using nestJs on 7.0.0 and if you do this:
@Get('/paramsTest3/:number/:name/:age')
getIdTest3(@Param() params:number): string{
console.log(params);
return this.appService.getMultipleParams(params);
}
The console.log(params)
result will be(the values are only examples):
{ number:11, name: thiago, age: 23 }
Upvotes: 6
Reputation: 59
You can get multiple params and map them to your dto in this way:
@Get('/login')
login(@Param() { userName, password }: LoginUserDto) {
console.log({ userName});
console.log({ password });
return 'OK'
}
Upvotes: 1
Reputation: 1078
Let's say you need to pass one required parameter named id
. You can send it through header params
, and your optional parameters can be sent via query params
:
@Get('/:id')
findAll(
@Param('id') patientId: string,
@Query() filter: string,
): string {
console.log(id);
console.log(filter);
return 'Get all samples';
}
Upvotes: 3
Reputation: 117
@Get('/login/:email/:password')
@ApiParam({name:'email',type:'string'})
@ApiParam({name:'password',type:'string'})
login(@Param() params: string[]) {
console.log(params)
return 'OK'
}
Output
{email:<input email >,password:<input password>}
Upvotes: 1
Reputation: 21207
Nest doesn't support the ability to automatically convert Get
query params into an object in this way. It's expected that you would pull out the params individually by passing the name of the param to the @Param
decorator.
Try changing your signature to:
login(@Param('userName') userName: string, @Param('password') password: string)
If you want to receive an object instead consider switching to using Post
and passing the object in the request body (which makes more sense to me for a login action anyways).
Upvotes: 11