Nestjs 拦截器
拦截器是使用@Injectable()装饰器注解的类。拦截器应该实现NestInterceptor接口。

这里学习拦截器,是为了避免接口被恶意调用,而做了一个限制拦截,从请求头判断请求来源,然后做相应的响应。
- 新建一个拦截器apiverification.interceptor.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import { Injectable,NestInterceptor,ExecutionContext,CallHandler, HttpException, HttpStatus } from '@nestjs/common' import { Observable} from 'rxjs'
@Injectable() export class apiverification implements NestInterceptor { intercept(content: ExecutionContext,next: CallHandler): Observable<any> { const response = content.switchToHttp().getResponse(); if(response.req.headers.origin !== 'http://xxx.xx'){ throw new HttpException({errcode: 40010, errmsg: '你无权调用API接口,也不应该使用该站点的任何数据来填充个人网站或其他用途。'}, HttpStatus.FORBIDDEN); } return next.handle() } }
|
非本站访问时,就会返回一个json
