controller与service
controller
要快速创建带有内置验证功能的 CRUD 控制器,可以使用 CLI 的CURD生成器:nest g resource [name]
对于ts的类型的定义可以引用 express 的类型定义
@Req() 原始请求对象(Request) @Req() req: Request @Res() 原始响应对象(Response) @Res() res: Response @Body() 获取请求体(JSON、form 等) @Body() body: any @Body('name') name: string @Query() 获取 URL 查询参数 @Query() query: any @Query('id') id: string @Param()
获取 URL 路径参数 @Param() params: any @Param('id') id: string
设置状态码
默认是200(除了POST请求外,POST是201)
更改状态码
import { Post, HttpCode } from '@nestjs/common';
@Post('login')
@HttpCode(204)
login() {
return { token: 'abc123' };
}
设置响应头
import { Post, Header } from '@nestjs/common';
@Post()
@Header('Cache-Control', 'no-store')
create() {
return 'This action adds a new cat';
}
重定向(在某个控制器方法执行后,自动跳转到另一个 URL)
@Redirect() 接收两个可选参数:url 和 statusCode。若省略 statusCode,其默认值为 302(Found)
import { Get, Redirect, } from '@nestjs/common'; @Get('redirect') @Redirect('https://nestjs.com', 302) home() { // 不返回任何内容,NestJS 会自动返回一个 302 响应,Location 是 nestjs.com }
前端请求不会自动跟随跳转
如果你用的是小程序、fetch、axios,要自己处理 3xx 响应
除非是浏览器直接访问
路由参数(例如通过 GET /mouse/1 获取 ID 为 1)
import { Get, Param, } from '@nestjs/common'; @Get('mouse/:id') findOne(@Param('id') id: string): string { return `This action returns a #${id} cat`; }
子域名路由(白名单)
@Controller({ host: 'admin.example.com' })
当请求的 Host 是 admin.example.com 时,这个控制器才会响应请求;如果是 www.example.com 或其他域名,请求将不会路由到这个控制器。
通配符为:,可以用@HostParam拿到域名前缀
如:请求:http://alice.example.com/account 的值为 "alice"
响应:This is alice's subdomain
@Controller({ host: ':account.example.com' })
export class AccountController {
@Get()
getAccount(@HostParam('account') account: string) {
return `This is account page for ${account}`;
}
}
| 写法 | 匹配示例 | 是否能取值 | 场景 |
|---|---|---|---|
:account.example.com |
alice.example.com |
✅ 是,用 @HostParam('account') |
多租户 |
*.example.com |
abc.example.com |
❌ 否 | 简单通配 |
example.com |
仅 example.com |
❌ 否 | 精确匹配 |
异步特性
若是调用数据库时
async findAll(): Promise<User[]> { return await this.userService.findAll(); } @Get() findAll(): Observable<any[]> { return of([]); }
异步代码是一次性请求-响应,推荐用 async + Promise,简单易用。
如果已经在用 RxJS 或需要流式处理,或者返回多个事件,可以用 Observable。
service
| 角色 | 作用 | 关注点 | 负责内容 |
|---|---|---|---|
| Controller | 处理请求,路由管理 | 请求/响应、路由映射 | 接收请求,调用 Service,返回响应 |
| Service | 业务逻辑实现 | 业务处理 | 具体业务逻辑、数据操作 |
浙公网安备 33010602011771号