Nest.js HTTP 传输方式
访问静态资源
- 在项目目录下创建 pubic 文件夹
- 在pubic文件夹下 创建静态资源 index.html 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
hello world
</body>
</html>
- main.ts 调用 useStaticAssets 方法支持静态资源请求
// 第一步 引入 NestExpressApplication
import { NestExpressApplication } from '@nestjs/platform-express';
async function bootstrap() {
// 第二步 给create 传入 NestExpressApplication app才能调用 useStaticAssets 方法
const app = await NestFactory.create<NestExpressApplication>(AppModule);
// 第三步 指定prefix 为 static 就可以访问静态资源了
app.useStaticAssets('public', { prefix: '/static'});
await app.listen(3000);
}
bootstrap();
- 浏览器调试
http://localhost:3000/static/(public里的文件名).html
五种接口写法 和 postman 调试
// 第一步 在模块下 dto 文件夹里的 create-person.dto.ts 定义 CreatePersonDto
export class CreatePersonDto {
name:string;
age:number;
}
// 第二步 在模块下的 controller.ts 里引入dto
import { CreatePersonDto } from './dto/create-person.dto';
第一种 url param GET 请求
@Get('find')
query(@Query('name') name: string, @Query('age') age: number) {
return `result: name=${name},age=${age}`;
}
- postman 调试
第二种 query GET 请求
@Get(':id')
urlParam(@Param('id') id: string) {
return `result: id=${id}`;
}
- postman 调试
第三种 form urlencoded POST 请求
@Post()
body(@Body() createPersonDto: CreatePersonDto) {
return `result: ${JSON.stringify(createPersonDto)}`;
}
- postman 调试
第四种 json POST 请求
@Post('submit')
body1(@Body() createPersonDto: CreatePersonDto) {
return `result: ${JSON.stringify(createPersonDto)}`;
}
- postman 调试
第五种 form data 文件上传
import { AnyFilesInterceptor } from '@nestjs/platform-express';
@Post('file')
@UseInterceptors(
AnyFilesInterceptor({
dest: 'uploads',
}),
)
body2(
@Body() createPersonDto: CreatePersonDto,
@UploadedFiles() files: Array<Express.Multer.File>,
) {
console.log(files);
return `result: ${JSON.stringify(createPersonDto)}`;
}
- postman 调试