拦截器
sonder 大杯

Nestjs 拦截器

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

这里学习拦截器,是为了避免接口被恶意调用,而做了一个限制拦截,从请求头判断请求来源,然后做相应的响应。

  • 新建一个拦截器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

image

  • 本文标题:拦截器
  • 本文作者:sonder
  • 创建时间:2020-09-17 17:45:56
  • 本文链接:https://sonderss.github.io/2020/09/17/拦截器/
 评论