Comments (1)
控制器 controllers
控制器负责处理传入的请求并将响应返回给客户端。
CRUD 生成器 CRUD generator:
nest g resource [name]
路由
@Controller()
装饰器 是定义一个基本控制器所必须的。
我们将指定一个可选的路径前缀为cats。
在@Controller()
装饰器中使用路径前缀可以让我们轻松地将一组相关的路由分组,并将重复的代码降到最低。
要使用 CLI 创建控制器,只需执行
nest g controller cats
命令
// cats.controller.tsJS
import { Controller, Get } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Get()
findAll(): string {
return 'This action returns all cats';
}
}
@Get()
HTTP请求方法装饰器告诉Nest为HTTP请求的特定端点创建一个处理程序
处理程序的路径是通过连接为控制器声明的(可选)前缀,以及方法装饰器中指定的任何路径来确定。
由于我们已经为每个路由(cats)声明了一个前缀,并且没有在装饰器中添加任何路径信息,Nest将把GET /cats
请求映射到这个处理器
路径包括可选的控制器路径前缀和请求方法装饰器中声明的任何路径字符串。
例如,customers的路径前缀与装饰器@Get('profile')
相结合,将产生一个GET /customers/profile
这样的路由映射请求。
例如,我们可以选择将一组管理与客户实体互动的路由归入路由
/customers
。
在这种情况下,我们可以在@Controller()
装饰器中指定路径前缀customers
,
这样我们就不必为文件中的每个路由重复这部分路径。
请求对象 Request object
处理程序经常需要访问客户端的请求细节。
Nest提供了对底层平台(默认为Express)的请求对象的访问。
我们可以通过在处理程序的签名中添加@Req()
装饰器来指示Nest注入请求对象来访问它。
为了利用
express
类型(如上面的参数示例request: Request
),安装@types/express
包。
//cats.controller.tsJS
import { Controller, Get, Req } from '@nestjs/common';
import { Request } from 'express';
@Controller('cats')
export class CatsController {
@Get()
findAll(@Req() request: Request): string {
return 'This action returns all cats';
}
}
请求对象 装饰器
请求对象代表了HTTP请求,并有请求查询字符串、参数、HTTP头和正文的属性(在此处阅读更多内容)。
在大多数情况下,没有必要手动抓取这些属性。
我们可以使用专门的装饰器来代替,比如@Body()
或@Query()
,这些装饰器开箱即用。
下面是一个所提供的装饰器的列表,以及它们所代表的普通平台特定对象。
@request(), @Req() | req |
---|---|
@response(), @res()* | 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] |
@ip() | req.ip |
@HostParam() | req.hosts |
为了与底层HTTP平台(如Express和Fastify)的类型兼容,Nest提供了
@Res()
和@Response()
装饰器。
@Res()
是@Response()
的简单别名。两者都直接暴露了底层的本地平台响应对象接口。
当使用它们时,你也应该导入底层库的类型(例如,@types/express
)以充分利用。
请注意,当你在方法处理程序中注入@Res()
或@Response()
时,你将Nest放入该处理程序的库特定模式中,并且你将负责管理响应。
当这样做时,你必须通过调用响应对象(如res.json(...)
或res.send(...)
)来发出某种响应,否则 HTTP 服务器将挂起。
要了解如何创建自己的自定义装饰器,请访问本章
资源 Resources#
一个创建新记录的端点
//cats.controller.tsJS
import { Controller, Get, Post } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Post()
create(): string {
return 'This action adds a new cat';
}
@Get()
findAll(): string {
return 'This action returns all cats';
}
}
Nest 为所有标准 HTTP 方法提供装饰器:
@Get()
、@Post()
、@Put()
、@Delete()
、@Patch()
、@Options()
和@Head()
. 此外,@All()
定义一个处理所有这些的端点。
路由通配符 Route wildcards#
也支持基于模式的路由。例如,星号用作通配符,将匹配任何字符组合
@Get('ab*cd')
findAll() {
return 'This route uses a wildcard';
}
'ab*cd'
路由路径将匹配abcd
,ab_cd
,abecd
等。
字符?
,+
,*
和()
可以在路由路径中使用,并且是它们的正则表达式对应物的子集。
连字符 (-
) 和点 (.
) 由基于字符串的路径逐字解释。
状态码 Status code#
如前所述,响应状态代码默认总是200,除了POST请求是201。
我们可以通过在处理程序级别添加@HttpCode(...)
装饰器来轻松改变这一行为。
@Post()
@HttpCode(204)
create() {
return 'This action adds a new cat';
}
HttpCode从
@nestjs/common
包中 导入。
通常,您的状态代码不是静态的,而是取决于各种因素。在这种情况下,您可以使用特定于库的响应(使用 注入
@Res()
)对象(或者,如果出现错误,则抛出异常)。
响应标头 Headers
要指定一个自定义的响应头,你可以使用
@Header()
装饰器或一个库特定的响应对象(并直接调用res.header()
)。
@Post()
@Header('Cache-Control', 'none')
create() {
return 'This action adds a new cat';
}
Header从
@nestjs/common
包中 导入。
重定向 Redirection#
要将一个响应重定向到一个特定的URL,你可以使用
@Redirect()
装饰器或一个库特定的响应对象(或直接调用res.redirect()
)。
@Redirect()
需要两个参数,url
和statusCode
,都是可选的。如果省略的话,statusCode
的默认值是302(Found)。
@Get()
@Redirect('https://nestjs.com', 301)
有时您可能希望动态确定 HTTP 状态代码或重定向 URL。通过从具有以下形状的路由处理程序方法返回一个对象来做到这一点:
{
"url": string,
"statusCode": number
}
返回值将覆盖传递给@reDIrect()装饰器的任何参数。例如:
@Get('docs')
@Redirect('https://docs.nestjs.com', 302)
getDocs(@Query('version') version) {
if (version && version === '5') {
return { url: 'https://docs.nestjs.com/v5/' };
}
}
路由参数 Route parameters#
当您需要接受动态数据作为请求的一部分时(例如,
GET /cats/1
获取带有 id 的 cat ),具有静态路径的路由将不起作用1。
为了定义带参数的路由,我们可以在路由的路径中添加路由参数标记,以捕获请求 URL 中该位置的动态值。
下面装饰器示例中的路由参数标记@Get()
演示了这种用法。
可以使用@Param()
装饰器访问以这种方式声明的路由参数,装饰器应添加到方法签名中。
@Get(':id')
findOne(@Param() params): string {
console.log(params.id);
return `This action returns a #${params.id} cat`;
}
@Param()
被用来装饰一个方法参数(上面例子中的params),并使路由参数作为该方法主体中被装饰的方法参数的属性可用。
正如上面的代码所见,我们可以通过引用params.id
来访问id
参数。
你也可以向装饰器传递一个特定的参数标记,然后在方法主体中直接引用路由参数的名称。
Param从
@nestjs/common
包中 导入
@Get(':id')
findOne(@Param('id') id: string): string {
return `This action returns a #${id} cat`;
}
子域路由 Sub-Domain Routing
@Controller
装饰器可以接受一个host
选项,要求传入请求的HTTP主机与某些特定值相匹配。
@Controller({ host: 'admin.example.com' })
export class AdminController {
@Get()
index(): string {
return 'Admin page';
}
}
由于Fastify缺乏对嵌套路由器的支持,所以在使用子域路由时,应该使用(默认)Express 适配器。
与路由路径类似,hosts选项可以使用令牌来捕获主机名称中该位置的动态值。
下面@Controller()
装饰器例子中的主机参数令牌展示了这种用法。
以这种方式声明的主机参数可以使用@HostParam()
装饰器进行访问,它应该被添加到方法签名中。
@Controller({ host: ':account.example.com' })
export class AccountController {
@Get()
getInfo(@HostParam('account') account: string) {
return account;
}
}
Scopes
对于来自不同编程语言背景的人来说,在 Nest 中得知几乎所有内容都是在传入请求之间共享的,这可能是出乎意料的。我们有一个到数据库的连接池、具有全局状态的单例服务等。请记住,Node.js 不遵循请求/响应多线程无状态模型,其中每个请求都由单独的线程处理。因此,使用单例实例对我们的应用程序来说是完全安全的。
然而,当控制器的基于请求的生命周期可能是期望的行为时,存在边缘情况,例如 GraphQL 应用程序中的每个请求缓存、请求跟踪或多租户。在此处了解如何控制范围。
异步 Asynchronicity
每个异步函数都必须返回一个Promise. 这意味着您可以返回 Nest 能够自行解析的延迟值。
//cats.controller.tsJS
@Get()
async findAll(): Promise<any[]> {
return [];
}
由于能够返回 RxJS可观察流,Nest 路由处理程序更加强大。Nest 将自动订阅下面的源并获取最后一个发出的值(一旦流完成)。
cats.controller.tsJS
@Get()
findAll(): Observable<any[]> {
return of([]);
}
请求有效载荷 Request payloads#
使用
@Body()
装饰器 接受任何客户端参数
DTO(数据传输对象)
但首先(如果你使用TypeScript),我们需要确定DTO(数据传输对象)模式。
DTO是一个定义了数据如何在网络上发送的对象。
我们可以通过使用TypeScript接口,或通过简单的类来确定DTO模式。
有趣的是,我们在这里推荐使用类。为什么呢?类是JavaScript ES6标准的一部分,因此它们在编译后的JavaScript中被保留为真实的实体。
另一方面,由于TypeScript接口在转译过程中被移除,Nest不能在运行时引用它们。
这一点很重要,因为像管道这样的功能在运行时可以访问变量的元类型,从而实现更多的可能性。
创建CreateCatDto类
create-cat.dto.tsJS
export class CreateCatDto {
name: string;
age: number;
breed: string;
}
它只有三个基本属性。此后我们可以在CatsController中使用新创建的DTO。
cats.controller.tsJS
@Post()
async create(@Body() createCatDto: CreateCatDto) {
return 'This action adds a new cat';
}
我们ValidationPipe可以过滤掉不应被方法处理程序接收的属性。在这种情况下,我们可以将可接受的属性列入白名单,任何未包含在白名单中的属性都会自动从结果对象中剥离。
在CreateCatDto示例中,我们的白名单是name、age和breed属性。在这里了解更多。
完整资源样本
下面是一个使用几个可用装饰器来创建基本控制器的示例。这个控制器公开了几个方法来访问和操作内部数据
cats.controller.tsJS
import { Controller, Get, Query, Post, Body, Put, Param, Delete } from '@nestjs/common';
import { CreateCatDto, UpdateCatDto, ListAllEntities } from './dto';
@Controller('cats')
export class CatsController {
@Post()
create(@Body() createCatDto: CreateCatDto) {
return 'This action adds a new cat';
}
@Get()
findAll(@Query() query: ListAllEntities) {
return `This action returns all cats (limit: ${query.limit} items)`;
}
@Get(':id')
findOne(@Param('id') id: string) {
return `This action returns a #${id} cat`;
}
@Put(':id')
update(@Param('id') id: string, @Body() updateCatDto: UpdateCatDto) {
return `This action updates a #${id} cat`;
}
@Delete(':id')
remove(@Param('id') id: string) {
return `This action removes a #${id} cat`;
}
}
启动并运行
在上述控制器完全定义后,Nest仍然不知道CatsController的存在,因此不会创建这个类的实例。
控制器总是属于一个模块,这就是为什么我们在
@Module()
装饰器中包含控制器数组。
因为除了根AppModule,我们还没有定义任何其他模块,所以我们将用它来介绍CatsController。
app.module.tsJS
import { Module } from '@nestjs/common';
import { CatsController } from './cats/cats.controller';
@Module({
controllers: [CatsController],
})
export class AppModule {}
我们使用
@Module()
装饰器将元数据附加到模块类,Nest现在可以很容易地反射出哪些控制器必须被安装。
特定于库的方法
到目前为止,我们已经讨论了操作响应的Nest标准方式。
操作响应的第二种方式是使用库的特定响应对象。
为了注入一个特定的响应对象,我们需要使用@Res()
装饰器。
为了显示差异,让我们把CatsController重写成以下内容。
import { Controller, Get, Post, Res, HttpStatus } from '@nestjs/common';
import { Response } from 'express';
@Controller('cats')
export class CatsController {
@Post()
create(@Res() res: Response) {
res.status(HttpStatus.CREATED).send();
}
@Get()
findAll(@Res() res: Response) {
res.status(HttpStatus.OK).json([]);
}
}
虽然这种方法是可行的,而且事实上通过提供对响应对象的完全控制,在某些方面确实有更大的灵活性(头文件的操作、库的特定功能等等),但应该谨慎使用。一般来说,这种方法不那么明确,而且确实有一些缺点。主要的缺点是,你的代码变得依赖于平台(因为底层库在响应对象上可能有不同的API),而且更难测试(你必须模拟响应对象,等等)。
另外,在上面的例子中,你失去了与依赖Nest标准响应处理的Nest功能的兼容性,如拦截器和
@HttpCode()
/@Header()
装饰器。为了解决这个问题,你可以将passthrough选项设置为true,如下所示。
@Get()
findAll(@Res({ passthrough: true }) res: Response) {
res.status(HttpStatus.OK);
return [];
}
现在,你可以与本地响应对象进行交互(例如,根据某些条件设置cookies或头信息),但把其他的事情留给框架。
from blog.
Related Issues (20)
- Stable Diffusion
- DALL·E 2
- Midjourney Styles ,Prompts
- 使用OrCAD Capture和PCB Editor进行完整PCB设计
- C# HOT 1
- MySQL HOT 3
- MetaGPT HOT 1
- stable diffusion webui HOT 11
- stable diffusion model 模型 HOT 5
- stable diffusion AI 模型训练
- Stable Diffusion 技巧 HOT 3
- ControlNet [stable diffusion] HOT 2
- Unity HOT 1
- GPT Prompt 提示词工程 HOT 2
- MetaGPT 源码分析报告 HOT 2
- ADI 亚德诺半导体 电子电气术语表 Glossary of EE Terms HOT 2
- stanford-agent-生成式代理 - 人类行为的交互式仿真
- Blender HOT 1
- 更便宜的3D MMO服务器:GPGPU
- C++ HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from blog.