创建控制器

nest g controller news

参数装饰器

@Request()    req
@Response()    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]

配置静态资源和模板引擎

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

import { join } from 'path'
import { NestExpressApplication } from '@nestjs/platform-express'
import { from } from 'rxjs';
// import { from } from 'rxjs';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  await app.listen(3000);
  // 配置静态资源
  app.useStaticAssets(join(__dirname,'..','public'))

   app.useStaticAssets('public')
  // 虚拟目录
  app.useStaticAssets('public',{
    prefix: '/static/'
  })

  // 配置模板引擎
  app.setBaseViewsDir('views')
  app.setViewEngine('ejs')

}
bootstrap();

创建服务

 nest g service admin

 ## 需要在module 中引入

文件上传

import { Controller, Post ,UseInterceptors, UploadedFile, Get} from '@nestjs/common';

import { createWriteStream } from 'fs';
import { join } from 'path'

import { FileInterceptor } from '@nestjs/platform-express'
// FileInterceptor 单图片上传
// FilesInterceptor 多图片上传


 @Post('upload')
  @UseInterceptors(FileInterceptor('file'))
  getUpload(@UploadedFile() file){
    console.log(file)
    var writeStream = createWriteStream(join(__dirname,'../public/upload',`${file.originalname}`),{encoding: 'utf8'})
    writeStream.write(file.buffer)
  } 

多文件上传

import { Controller, Get , Post, UseInterceptors, UploadedFile, UploadedFiles} from '@nestjs/common';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express'
import { AppService } from './app.service';

import { createWriteStream } from 'fs';
import { join } from 'path'

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }

  // 单文件上传
  @Post('upload')
  @UseInterceptors(FileInterceptor('file'))
  getUpload(@UploadedFile() file){
    console.log(file)
    var writeStream = createWriteStream(join(__dirname,'../public/upload',`${file.originalname}`),{encoding: 'utf8'})
    writeStream.write(file.buffer)
  } 

  // 多文件上传
  @Post('uploadall')
  @UseInterceptors(FilesInterceptor('file'))
  getUploadAll(@UploadedFiles() file){
    console.log(file)
    return ''
  }
}

中间件

命令行创建

 nest g middleware init

管道

nest g pipe user

HTML小白呀
22 声望0 粉丝

引用和评论

0 条评论