Nest.js 路由参数没有返回任何东西
Nest.js route param is not returning anything
我开始学习了Nest.js。现在我想了解路由参数是如何工作的。
我有一个带有以下代码的控制器。
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;
}
}
如您在代码中所见,我正在尝试检索名称参数。但是,当我在浏览器中访问此 URL http://localhost:3000/?name=test 时,出现以下错误。
http://localhost:3000/?name=test
当我转到这个 URL 时,http://localhost:3000/test,它只是不断加载页面。我的代码有什么问题,我该如何解决?
有 2 种参数装饰器。
- 路由参数
@Param('name') param: string
在您使用 http://localhost:3000/:name
的客户端上
你会得到 name
as string
使用邮递员 http://localhost:3000/john
@Get(':name')
getHello(@Param('name') name: string,
@Req() req: Request,
@Res() res: Response): string {
return name;
}
- 查询参数
@Query() query: {[key: string]: string}
在您使用 http://localhost:3000/?name=test&age=40
的客户端上
你得到的对象是{name: "test", age: "40"}
使用两者的示例
@Get(':name')
getHello(@Param('name') name: string,
@Query() query: {age: string}
@Req() req: Request,
@Res() res: Response): string {
return name;
}
使用邮递员 localhost:3000/john?age=30
您可以从 @Query
获取年龄,从 @Param
获取姓名
另请注意,如果您不使用 Request DTO
,使用数字 if @Query
将始终被解析为字符串
我开始学习了Nest.js。现在我想了解路由参数是如何工作的。
我有一个带有以下代码的控制器。
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;
}
}
如您在代码中所见,我正在尝试检索名称参数。但是,当我在浏览器中访问此 URL http://localhost:3000/?name=test 时,出现以下错误。
http://localhost:3000/?name=test
当我转到这个 URL 时,http://localhost:3000/test,它只是不断加载页面。我的代码有什么问题,我该如何解决?
有 2 种参数装饰器。
- 路由参数
@Param('name') param: string
在您使用http://localhost:3000/:name
的客户端上 你会得到name
as string
使用邮递员 http://localhost:3000/john
@Get(':name')
getHello(@Param('name') name: string,
@Req() req: Request,
@Res() res: Response): string {
return name;
}
- 查询参数
@Query() query: {[key: string]: string}
在您使用http://localhost:3000/?name=test&age=40
的客户端上 你得到的对象是{name: "test", age: "40"}
使用两者的示例
@Get(':name')
getHello(@Param('name') name: string,
@Query() query: {age: string}
@Req() req: Request,
@Res() res: Response): string {
return name;
}
使用邮递员 localhost:3000/john?age=30
您可以从 @Query
获取年龄,从 @Param
另请注意,如果您不使用 Request DTO
,使用数字 if@Query
将始终被解析为字符串