装饰器
Nestjs提供了一些方法参数装饰器,用于快速获取参数:
装饰器 | 方法参数 |
---|
@Request() | req |
@Response() | res |
@Next() | next |
@Session() | req.session |
@Param(key?: string) | req.params/req.params[key] |
@Body(key?: string) | req.body/req.body[key] |
@Query(key?: string) | req.query/req.query[key] |
@Headers(name?: string) | req.headers/req.headers[name] |
@HttpCode | |
获取Get请求传参
接口:
1 2 3 4 5 6 7 8 9 10 11 12 13
| @Get() findAll(@Request() req) { console.log(req.query); return { code: 200 }; }
@Get() findAll(@Query() query) { console.log(query); return { code: 200 }; }
|
请求:
1
| http://localhost:3000/user?omg=114514&yee=1919810
|
后台控制台输出:
1
| { omg: '114514', yee: '1919810' }
|
Post获取参数
接口:
1 2 3 4 5 6 7 8 9 10 11 12 13
| @Post() create(@Request() req) { console.log(req.body); return { code: 200 }; }
@Post() create(@Body() body) { console.log(body); return { code: 200 }; }
|
请求:
1
| http://localhost:3000/user
|
携带Body:
后台控制台输出:
动态路由
接口:
1 2 3 4 5 6 7 8 9 10 11 12
| @Get(':id') findOne(@Param('id') id: string) { return this.userService.findOne(+id); }
@Get() findAll(@Param() params) { console.log(params); return { code: 200 }; }
|
请求:
1
| http://localhost:3000/user/114514
|
后台控制台输出:
接口:
1 2 3 4 5 6 7 8 9 10 11 12 13
| @Get() findOne(@Request() req) { console.log(req.headers); return { code: 200 }; }
@Get() findOne(@Headers() headers) { console.log(headers); return { code: 200 }; }
|
请求:
1
| http://localhost:3000/user
|
后台控制台输出:
1 2 3 4 5 6 7 8 9
| { 'user-agent': 'PostmanRuntime/7.32.2', accept: '*/*', 'postman-token': '1b5d9bc5-3a96-4607-af1d-b50fe206f524', host: 'localhost:3000', 'accept-encoding': 'gzip, deflate, br', connection: 'keep-alive', cookie: 'NMTID=00OM0h1Jr9fGdUkMUdgm34oN5ryRH8AAAGBk5jICQ' }
|
控制状态码
接口:
1 2 3 4 5 6
| @Get() @HttpCode(500) findAll() { console.log(); return { code: 200 }; }
|
请求:
1
| http://localhost:3000/user
|
前台收到的响应状态码:
1
| 500Internal Server Error
|