准备
搭建了nestjs项目之后,先要安装swagger包方便做接口调试,安装命令
npm install --save @nestjs/swagger swagger-ui-express
然后在main.ts中使用(这里我直接将我的代码粘过来了)
- main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { NestExpressApplication } from '@nestjs/platform-express';
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
// 为了启用 CORS,必须调用 enableCors() 方法。
app.enableCors()
const options = new DocumentBuilder()
.setTitle('Cats example')
.setDescription('The cats API description')
.setVersion('1.0')
.addTag('cats')
.build();
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('api', app, document);
await app.listen(3000);
console.log(`http://localhost:${3000}/api`)
}
bootstrap();
swagger的基本操作
运行项目你会发现这样一个地址,然后点他!!!
然后浏览器就会出现这样一个界面
这里出现了项目中自带的接口,那么怎么在swagger中调这个接口呢,如图
经过哪里亮了点哪里的一顿操作之后呢,就得到了接口返回的结果了,是不是很简单呢。
既然是接口肯定少不了传参呢,肯定不是这么简单的,那么在下面边写接口边说吧
热部署
说白了就是项目不停的情况下把修改的代码运行起来,之前不是说每改一次代码都要重启项目很麻烦嘛,启动项目的时候可以试试用这个命令启动就好了
nest start --watch
控制器
终于要开始写接口了,对于控制器的解释官网是这么说的:控制器负责处理传入的请求和向客户端返回响应。
什么意思不重要,咱们就是要用控制器写接口就对了,用就完了
Get 请求写法
首先先创建一个shop文件夹,然后创建文件shop.controller.ts,内容如下
import { Controller, Get, Param, Query, Req } from '@nestjs/common';
@Controller('shop')
export class ShopController {
@Get('list/:id')
find(@Param('id') id: string): string {
return '一些商品'+id;
}
}
然后在 app.module.ts中将ShopController导入(因为改了名字的缘故我这个的名字可能有些差异比如我的是Admin…,领会精神即可)
然后就会发现在swagger中多了一项
然后点击Try it out并将id填入来试试效果
这里看到参数传进来了并且也接收到了,我来说说上面的三个装饰器都是做什么的
- @Controller 主要是进行路由分组,比如在类ShopController写了
@Controller('shop')
,这就说明类ShopController所写的接口都在路由shop下 - @Get 访问方式为Get请求,里面的参数为访问路径,:id为后面接的是动态参数,并且参数名为id
- @Param 路由参数
可能会觉得这么创建有些麻烦,那试试这个命令
nest g controller cats
,会有不一样的事情发生哦
POST请求写法
其实也不神奇啦,无非就是运行完命令出现了个文件夹,免得自己手动创建了嘛
先在cats里创建文件夹dto然后创建文件create-cat.dto.ts
export class CreateCatDto {
readonly name: string;
readonly age: number;
readonly breed: string;
}
然后在这里写一个POST请求的写法
- cats.controller.ts
import { Body, Controller, Delete, Get, HttpStatus, Param, Post, Put, Query, Redirect, Req, Res } from '@nestjs/common';
import { CreateCatDto } from './dto/create-cat.dto';
@Controller('cats')
export class CatsController {
@Post()
create(@Body() createCatDto: CreateCatDto) {
return 'This action adds a new cat ' + createCatDto.name;
}
}
然后在swagger中调一下
- @Post说明是POST请求
- @Body是POST请求接受的参数至于这里创建个CreateCatDto是为了约束传参类型
其他请求写法
我就直接贴代码了,感兴趣可以自己在swagger里面玩玩
import { Body, Controller, Delete, Get, HttpStatus, Param, Post, Put, Query, Redirect, Req, Res } from '@nestjs/common';
import { CreateCatDto } from './dto/create-cat.dto';
import { ListAllEntities } from './dto/ListAllEntities';
import { UpdateCatDto } from './dto/update-cat.dto';
@Controller('cats')
export class CatsController {
@Post()
create(@Body() createCatDto: CreateCatDto) {
return 'This action adds a new cat ' + createCatDto.name;
}
@Get('black/:id')
findGet(@Param('id') id: string, @Query() query: ListAllEntities) {
return `This action returns black 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`;
}
}
重定向
如果想要请求跳到指定的url那么这个你可能就需要了
import { Body, Controller, Delete, Get, HttpStatus, Param, Post, Put, Query, Redirect, Req, Res } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Get()
@Redirect('https://baidu.com', 301)
@Get('docs')
@Redirect('https://baidu.com', 301)
getDocs(@Query('version') version) {
if (version && version === '5') {
return { url: 'https://docs.nestjs.com/v5/' };
}
}
}
- 上面的方法是直接跳转写法,下面是做些逻辑判断写法