一、拦截器
拦截器作用:
- 在函数执行之前、之后绑定额外的逻辑
- 转换函数的返回结果
- 转换从函数抛出的异常
- 扩展基本函数的行为
- 根据所选条件重写函数
期望接口返回一个标准的json格式,利用拦截器对数据做全局的格式化
{
    code: "200",
    data: [],
    message: "操作成功!"
}二、拦截器实现
创建文件 common/response.ts

import { Injectable, NestInterceptor, CallHandler } from "@nestjs/common";
import { Observable } from "rxjs";
import { map } from 'rxjs/operators';
interface data<T>{
    data: T
}
@Injectable ()
export class Response<T = any> implements NestInterceptor {
    intercept(context, next: CallHandler): Observable<data<T>> {
        return next.handle().pipe(map(data => {
            return {
                data,
                code: '200',
                message: '操作成功!'
            }
        }))
    }
}三、main.ts 中注册全局拦截器
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express/interfaces';
import { Response } from './common/response';
import { AppModule } from './app.module';
async function bootstrap() {
    const app = await NestFactory.create<NestExpressApplication>(AppModule);
    app.useGlobalInterceptors(new Response())
    await app.listen(3000);
}
bootstrap();四、浏览器访问















![[BJDCTF 2020]Easy](https://img-blog.csdnimg.cn/direct/26bb607deff243c2b5c47ac06d6b9fb1.png)




