1.nestJS创建子模块
大家如果学过angular 命令其实很像的
nest -h (呼出帮助命令)
绿色的是全名,蓝色的是别名
创建一个controller
nest g co index
创建子module
nest g mo index

2.nest路由
@Controller()
装饰器中使用路径前缀可以使我们轻松地对一组相关的路由进行分组,并最大程度地减少重复代码
@Get()
HTTP 请求方法装饰器告诉 Nest 为 HTTP 请求的特定端点创建处理程序。端点对应于 HTTP
请求方法(在本例中为 GET
import { Controller, Get } from '@nestjs/common';
@Controller('index')
export class IndexController {
@Get()
list() {
return [1, 2, 3]
}
}
参数装饰器
@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 |
get 用query,post用body
import { Body, Controller, Get, Header, HttpCode, Param, Post, Query, Req } from '@nestjs/common';
@Controller('index')
export class IndexController {
@Post()
list(@Body() body ):any {
return body
}
}
import { Body, Controller, Get, Header, HttpCode, Param, Post, Query, Req } from '@nestjs/common';
@Controller('index')
export class IndexController {
@Get()
list(@Query() query ):any {
return query
}
}
query 和 body 都可以接受参数
import { Body, Controller, Get, Header, HttpCode, Param, Post, Query, Req } from '@nestjs/common';
@Controller('index')
export class IndexController {
@Get()
list(@Query('age') query ):any {
return query
}
}
这样就直接读取age 的值并返回
动态路由(跟vue用法一样冒号后面跟参数)param 接受参数
import { Body, Controller, Get, Header, HttpCode, Param, Post, Query, Req } from '@nestjs/common';
@Controller('index')
export class IndexController {
@Get(':id')
list(@Param('id') query): any {
return query
}
}
@HttpCode(500)
响应的状态码总是默认为 200,除了 POST 请求(默认响应状态码为 201),我们可以通过在处理函数外添加 @HttpCode(...)
装饰器来轻松更改此行为。
import { Body, Controller, Get, Header, HttpCode, Param, Post, Query, Req } from '@nestjs/common';
@Controller('index')
export class IndexController {
@Get(':id')
@HttpCode(500)
list(@Param('id') query): any {
return query
}
}
@Header('Cache-Control', 'none')
要指定自定义响应头,可以使用 @header()
装饰器或类库特有的响应对象,(并直接调用 res.header()
)。
import { Body, Controller, Get, Header, HttpCode, Param, Post, Query, Req } from '@nestjs/common';
@Controller('index')
export class IndexController {
@Get(':id')
@Header('Cache-Control', 'none')
list(@Param('id') query): any {
return query
}
}