nest.js控制器: 控制器负责处理传入请求并向客户端返回响应。
为了创建基本控制器,我们使用类和装饰器。装饰器将类与所需的元数据相关联,并使 Nest 能够创建路由映射(将请求绑定到相应的控制器)。
1.获取get请求传参,用@Request装饰器或者@Query()装饰器
import {
Controller,
Get,
Request,
} from '@nestjs/common';
import { WeiService } from './wei.service';
@Controller({
path: 'wei',
version: '1', //版本控制
})
export class WeiController {
constructor(private readonly weiService: WeiService) { }
// @Request装饰器
@Get()
findAll(@Request() req) {
console.log('@', req.query)
return {
code: 200,
message: '请求成功W'
}
}
}
import {
Controller,
Get,
Query,
} from '@nestjs/common';
import { WeiService } from './wei.service';
@Controller({
path: 'wei',
version: '1', //版本控制
})
export class WeiController {
constructor(private readonly weiService: WeiService) { }
// @Query()装饰器
@Get()
findAll(@Query() query) {
console.log('@@', query)
return {
code: 200,
message: '请求Q成功'
}
}
}
2.post请求获取参数,用@Request装饰器或者@Body 装饰器
import {
Controller,
Get,
Query,
} from '@nestjs/common';
import { WeiService } from './wei.service';
@Controller({
path: 'wei',
version: '1',
})
export class WeiController {
constructor(private readonly weiService: WeiService) { }
//用@Request装饰器
@Post()
create(@Request() req) {
console.log(req.body)
return {
code: 200,
message: '请求成功!'
}
}
}
import {
Controller,
Get,
Query,
} from '@nestjs/common';
import { WeiService } from './wei.service';
@Controller({
path: 'wei',
version: '1',
})
export class WeiController {
constructor(private readonly weiService: WeiService) { }
//用@Body装饰器
@Post()
create(@Body() body) {
console.log(body)
return {
code: 200,
message: '请求成功!'
}
}
}
读取请求体中得key值
import {
Body,
Controller,
} from '@nestjs/common';
import { WeiService } from './wei.service';
@Controller({
path: 'wei',
version: '1',
})
export class WeiController {
constructor(private readonly weiService: WeiService) { }
// 读取key
@Post()
create(@Body("title") body) {
console.log(body)
return {
code: 200,
message: '请求成功'
}
}
}
动态传参使用 Request装饰器 或者 Param 装饰器
import {
Controller,
Request,
} from '@nestjs/common';
import { WeiService } from './wei.service';
@Controller({
path: 'wei',
version: '1',
})
export class WeiController {
constructor(private readonly weiService: WeiService) { }
// 动态路由
// Request装饰器 或者 Param 装饰器
@Get(':id')
findId(@Request() req) {
console.log('@@@@@@', req.params)
return {
code: 200,
message: '请求成功!!!!!!'
}
}
}
header信息读取使用@header装饰器
import {
Controller,
Get,
Headers,
} from '@nestjs/common';
import { WeiService } from './wei.service';
@Controller({
path: 'wei',
version: '1',
})
export class WeiController {
constructor(private readonly weiService: WeiService) { }
// 读取header 信息
@Get(':id')
findId(@Headers() header) {
console.log('header', header)
return {
code: 200,
message: '请求成功!!!!!!'
}
}
}