Nestjs 笔记

一、模块添加版本

1、添加如下代码

2、访问方式

复制代码
 http://localhost:3000/v1/list

二、跨域处理

1、安装依赖

复制代码
npm install cors

npm install @types/cors -D

2、app.module.ts 添加代码

TypeScript 复制代码
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as cors from 'cors'
 
const whiteList = ['/list']
 
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use(cors())
  await app.listen(3000);
}
bootstrap();

三、中间件

中间件是在路由处理程序之前调用的函数,中间件函数可以访问请求和响应对象

中间件函数可以执行一下任务

  • 执行任何代码
  • 对请求和响应对象进行更改
  • 结束请求-响应周期
  • 调用堆栈中的下一个中间件函数
  • 如果当前的中间件函数没有结束请求-响应周期,它必须嗲用next()将控制传递给下一个中间件函数,否则请求将被挂起!

1、全局中间件

TypeScript 复制代码
import { VersioningType } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as session from 'express-session';

const whiteList = ['/list'];

function middleWareAll (req, res, next) {
    console.log(req.originalUrl, '全局中间件');
    if(whiteList.includes(req.originalUrl)){
        next();
    }else{
        res.send('无权限!');
    }
}

async function bootstrap() {
    const app = await NestFactory.create(AppModule);
    app.enableVersioning({
        type: VersioningType.URI
    })
    app.use(session({secret: "WangShan", name: "xm.session", rolling: true, cookie: { maxAge: null}}));
    app.use(middleWareAll);
    await app.listen(3000);
}
bootstrap();
相关推荐
_落纸2 天前
三大基础无源电子元件——电阻(R)、电感(L)、电容(C)
笔记
Alice-YUE2 天前
【CSS学习笔记3】css特性
前端·css·笔记·html
2303_Alpha2 天前
SpringBoot
笔记·学习
Hello_Embed2 天前
STM32HAL 快速入门(二十):UART 中断改进 —— 环形缓冲区解决数据丢失
笔记·stm32·单片机·学习·嵌入式软件
咸甜适中2 天前
rust语言 (1.88) 学习笔记:客户端和服务器端同在一个项目中
笔记·学习·rust
Grassto2 天前
RAG 从入门到放弃?丐版 demo 实战笔记(go+python)
笔记
Magnetic_h2 天前
【iOS】设计模式复习
笔记·学习·ios·设计模式·objective-c·cocoa
周周记笔记2 天前
学习笔记:第一个Python程序
笔记·学习
丑小鸭是白天鹅3 天前
Kotlin协程详细笔记之切线程和挂起函数
开发语言·笔记·kotlin
潘达斯奈基~3 天前
《大数据之路1》笔记2:数据模型
大数据·笔记