Nest技巧

1.第三方中间件 cors 处理跨域

npm install cors

npm install @types/cors -D

// 接入第三方中间件 cors 处理跨域
import * as cors from 'cors'
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // 使用 cors 处理跨域
  app.use(cors())
  await app.listen(3000);
}
 

2.全局中间件,可做白名单拦截之类的

// 全局中间件,可做白名单拦截之类的
const whiteList = ['/list']
function middleWareAll(req,res,next){
  console.log(req.originalUrl,'我是全局的,访问http://localhost:3000/list会被捕获')
  if(whiteList.includes(req.originalUrl)){
    next()
  }else{
    res.send('小黑子露出鸡脚了吧,被拦截了')
  }
}

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // 调用全局中间件
  app.use(middleWareAll)
  await app.listen(3000);
}

 

3.上传图片

multer   @nestjs/platform-express nestJs自带了

multer   @types/multer 这两个需要安装

参考

https://xiaoman.blog.csdn.net/article/details/126796646

 

4.下载图片 

有2种方法

参考

https://xiaoman.blog.csdn.net/article/details/126880230

1.download 直接下载

 

2.使用文件流的方式下载

可以使用compressing把他压缩成一个zip包

import {zip} from 'compressing'

 

5.用nest 脚手架创建新项目

先安装脚手架,再创建新项目project-name

$ npm i -g @nestjs/cli
$ nest new project-name

 

 

posted @ 2023-05-19 13:23  泠风lj  阅读(92)  评论(0编辑  收藏  举报