代码
@Query 可接收接口路径中传入的参数
@Body 可接收body中传入的参数
@Headers 可接收Headers中传入的参数
import { Controller, Post, Get, Body, Query, Headers } from '@nestjs/common';
// 定义getList参数类型
export class ListDto {
readonly page: number;
readonly pageSize: number;
}
// 定义createData参数类型
export class CreateCatDto {
readonly name: string;
readonly age: number;
readonly breed: string;
}
@Controller('cats')
export class CatsController {
// 接收接口路径传参 get请求 【功能:获取列表】
@Get()
async getList(@Query() params: ListDto) {
return `页码:${params.page},条数:${params.pageSize}`;
}
// 接收body传参 post请求 【功能:插入数据】
@Post()
async createData(@Body() params: CreateCatDto) {
return `名称:${params.name},年龄:${params.age}`;
}
// 接收headers传参 post请求 【功能:获取用户信息】
@Post('userInfo') //子路由userInfo
async getUserInfo(@Headers() params) {
return `用户id:${params.id}`;
}
}
接口测试
- 接口路径传参
- 接收body传参
- 接收headers传参