nest各模块学习

跨域解决

安装

npm install cors
npm install @types/cors -D

src/main.ts里面引入一下

import {
    NestFactory } from '@nestjs/core';
import {
    AppModule } from './app.module';
// 引入cors
import * as cors from 'cors'
async function bootstrap() {
   
  const app = await NestFactory.create(AppModule);
  // 注册cors
  app.use(cors())
  await app.listen(3000);
}
bootstrap();

验证码实现思路

安装

npm install svg-captcha --save

创建一个验证码模块

nest g res yanzhengma

// 回车后选择REST API
// 再输入yes
// 再次回车即可

在验证码模块的yanzhengma.controller.ts里面实现如下:

import {
   
  Controller,
  Get,
  Post,
  Body,
  Param,
  Request,
  Query,
  Headers,
  HttpCode,
  Res,
  Req,
} from '@nestjs/common';
import {
    YanzhengmaService } from './yanzhengma.service';
import {
    CreateYanzhengmaDto } from './dto/create-yanzhengma.dto';
import {
    UpdateYanzhengmaDto } from './dto/update-yanzhengma.dto';
import * as svgCaptcha from 'svg-captcha';
@Controller('yanzhengma')
export class YanzhengmaController {
   
  constructor(private readonly yanzhengmaService: YanzhengmaService) {
   }
  // 浏览器访问:http://localhost:3000/yanzhengma/code 就可以看到验证码图片
  @Get('code')
  createCaptcha() {
   
    const captcha = svgCaptcha.create({
   
      size: 4, //生成几个验证码
      fontSize: 50, //文字大小 
      width: 100, //宽度
      height: 34, //高度
      background: '#cc9966', //背景颜色
    });
    // captcha 是一个对象,包含了验证码图片和验证码内容文字
    // res.type('image/svg+xml'); // 这样是直接返回验证码图片,不会经过下面的逻辑了
    console.log(captcha);
    
    return captcha; // 将验证码图片返回给前端
  }
}

共享模块

新建一个共享模块

nest g res 模块名

// 回车后选择REST API
// 再输入yes
// 再次回车即可

我这里模块名还是以yanzhengma为例

yanzhengma.module.ts里面将模块导出,内容如下:

import {
    Module } from '@nestjs/common';
import {
    YanzhengmaService } from './yanzhengma.service';
import {
    YanzhengmaController } from './yanzhengma.controller';

@Module({
   
  controllers: [YanzhengmaController],
  providers: [YanzhengmaService],
  exports: [YanzhengmaService],
})
export class YanzhengmaModule {
   }

在其他模块就可以使用yanzhengma模块的方法了,如下在app.controller.ts里面引入yanzhengma.service,然后就可以直接调用其方法

import {
    Controller, Get } from '@nestjs/common';
import {
    AppService } from './app.service';
import {
    YanzhengmaService } from './yanzhengma/yanzhengma.service';

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

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

这时浏览器访问http://localhost:3000/就可以看到yanzhengma.service里面的findAll方法返回的信息了

中间件

创建中间件模版

nest g mi logger // 最后一个是模块名

模版内容如下:

import {
    Injectable, NestMiddleware } from '@nestjs/common';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
   
  use(req: any, res: any, next: () => void) {
   
    console.log('我是中间件');
    next();
  }
}

局部中间件

使用中间件

任意模块内引入中间件,例如我这里还是以yanzhengma模块为例

yanzhengma.module.ts里面进行引入

import {
    MiddlewareConsumer, Module, NestModule, RequestMethod } from '@nestjs/common';
import {
    YanzhengmaService } from './yanzhengma.service';
import {
    YanzhengmaController } from './yanzhengma.controller';
import {
    LoggerMiddleware } from 'src/logger/logger.middleware';
@Module({
   
  controllers: [YanzhengmaController],
  providers: [YanzhengmaService],
  exports: [YanzhengmaService],
})
export class YanzhengmaModule implements NestModule {
   
  configure(consumer: MiddlewareConsumer) {
   
    // 方式一
    // consumer.apply(LoggerMiddleware).forRoutes('yanzhengma'); // yanzhengma为当前模块的controller的@Controller('yanzhengma')里面的参数,可以拦截/yanzhengma和子路径所有请求

    // 方式二
    // consumer.apply(LoggerMiddleware).forRoutes({path: 'yanzhengma', method: RequestMethod.GET}); // 只拦截验证码模块的get请求,并且访问路径只能是/yanzhengma,如/yanzhengma/code就不能被拦截
    // consumer.apply(LoggerMiddleware).forRoutes({path: 'yanzhengma/code', method: RequestMethod.POST}); // 只拦截验证码模块的get请求,并且访问路径只能是/yanzhengma/code

    // 方式三
    consumer.apply(LoggerMiddleware).forRoutes(YanzhengmaController); // 直接将当前控制器所有的请求都拦截了
  }
}

全局中间件

main.ts里面更换为如下代码:

import {
    NestFactory } from '@nestjs/core';
import {
    AppModule } from './app.module';
// 引入cors
import * as cors from 'cors'
import {
    Request,Response,NextFunction } from 'express';

// 定义全局中间件函数
function middleWareAll(req: Request, res: Response, next: NextFunction){
   
  console.log('当前访问的路由地址为',req.originalUrl); // 获取请求的路由地址
  next()
}

async function bootstrap() {
   
  const app = await NestFactory.create(AppModule);
  // 注册cors
  app.use(cors())
  // 注册全局中间件
  app.use(middleWareAll)
  await app.listen(3000);
}
bootstrap();

响应拦截器

创建响应拦截器模块

nest g interceptor yanzhengma

src/yanzhengma/yanzhengma.interceptor.ts文件内加入以下代码

import {
    CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import {
    Observable,map } from 'rxjs';

@Injectable()
export class YanzhengmaInterceptor implements NestInterceptor {
   
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
   
    return next.handle().pipe(
      map((data) => {
   
        return {
   
          data,
          code: 0,
          msg: '接口请求成功',
        };
      }),
    );
  }
}

main.ts进行引入

import {
    NestFactory } from '@nestjs/core';
import {
    AppModule } from './app.module';
// 引入cors
import * as cors from 'cors'
import {
    Request
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

萧寂173

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值