一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導航

node.js|vue.js|jquery|angularjs|React|json|js教程|

服務(wù)器之家 - 編程語言 - JavaScript - js教程 - nestjs返回給前端數(shù)據(jù)格式的封裝實現(xiàn)

nestjs返回給前端數(shù)據(jù)格式的封裝實現(xiàn)

2022-01-22 18:55水痕01 js教程

這篇文章主要介紹了nestjs返回給前端數(shù)據(jù)格式的封裝實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

一般開發(fā)過程中不不會根據(jù)httpcode來判斷接口請求成功與失敗的,而是會根據(jù)請求返回的數(shù)據(jù),里面加上code字段

一、返回的數(shù)據(jù)格式對比

1、直接返回的數(shù)據(jù)格式

?
1
2
3
4
5
6
7
8
9
{
  "id": 1,
  "uuid": "cbbe7abc-b95e-48a0-8d24-b1ac93c45328",
  "name": "哈士奇1",
  "age": 12,
  "color": null,
  "createAt": "2019-07-25T09:13:30.000Z",
  "updateAt": "2019-07-25T09:13:30.000Z"
}

2、我們自己包裝后的返回數(shù)據(jù)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
{
 code: 0,
 message: "請求成功",
 data: {
  "id": 1,
  "uuid": "cbbe7abc-b95e-48a0-8d24-b1ac93c45328",
  "name": "哈士奇1",
  "age": 12,
  "color": null,
  "createAt": "2019-07-25T09:13:30.000Z",
  "updateAt": "2019-07-25T09:13:30.000Z"
 }
}

二、攔截全部的錯誤請求,統(tǒng)一返回格式

1、使用命令創(chuàng)建一個過濾器

?
1
nest g f filters/httpException

2、過濾器的代碼

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import {
 ArgumentsHost,
 Catch,
 ExceptionFilter,
 HttpException,
 HttpStatus,
 Logger,
} from '@nestjs/common';
 
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
 catch(exception: HttpException, host: ArgumentsHost) {
  const ctx = host.switchToHttp();
  const response = ctx.getResponse();
  const request = ctx.getRequest();
 
  const message = exception.message.message;
  Logger.log('錯誤提示', message);
  const errorResponse = {
   data: {
    error: message,
   }, // 獲取全部的錯誤信息
   message: '請求失敗',
   code: 1, // 自定義code
   url: request.originalUrl, // 錯誤的url地址
  };
  const status =
   exception instanceof HttpException
    ? exception.getStatus()
    : HttpStatus.INTERNAL_SERVER_ERROR;
  // 設(shè)置返回的狀態(tài)碼、請求頭、發(fā)送錯誤信息
  response.status(status);
  response.header('Content-Type', 'application/json; charset=utf-8');
  response.send(errorResponse);
 }
}

3、在main.ts中全局注冊

?
1
2
3
4
5
6
7
8
9
...
import { HttpExceptionFilter } from './filters/http-exception.filter';
 
async function bootstrap() {
 ...
 // 全局注冊錯誤的過濾器
 app.useGlobalFilters(new HttpExceptionFilter());
}
bootstrap();

4、測試,返回的錯誤信息

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
 "statusCode": 400,
 "error": "Bad Request",
 "data": {
  "message": [
   {
    "age": "必須的整數(shù)"
   }
  ]
 },
 "message": '請求失敗',
 "code": 1,
 "url": "/api/v1/cat"
}

三、統(tǒng)一請求成功的返回數(shù)據(jù)

1、創(chuàng)建一個攔截器src/interceptor/transform.interceptor.ts

2、攔截器的代碼

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import {
 Injectable,
 NestInterceptor,
 CallHandler,
 ExecutionContext,
} from '@nestjs/common';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
interface Response<T> {
 data: T;
}
@Injectable()
export class TransformInterceptor<T>
 implements NestInterceptor<T, Response<T>> {
 intercept(
  context: ExecutionContext,
  next: CallHandler<T>,
 ): Observable<Response<T>> {
  return next.handle().pipe(
   map(data => {
    return {
     data,
     code: 0,
     message: '請求成功',
    };
   }),
  );
 }
}

3、全局注冊

?
1
2
3
4
5
6
7
8
9
10
...
import { TransformInterceptor } from './interceptor/transform.interceptor';
 
async function bootstrap() {
 ...
 // 全局注冊攔截器
 app.useGlobalInterceptors(new TransformInterceptor());
 ...
}
bootstrap();

4、測試返回數(shù)據(jù)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
{
 "data": {
  "id": 1,
  "uuid": "cbbe7abc-b95e-48a0-8d24-b1ac93c45328",
  "name": "哈士奇1",
  "age": 12,
  "color": null,
  "createAt": "2019-07-25T09:13:30.000Z",
  "updateAt": "2019-07-25T09:13:30.000Z"
 },
 "code": 0,
 "message": "請求成功"
}

到此這篇關(guān)于nestjs返回給前端數(shù)據(jù)格式的封裝實現(xiàn)的文章就介紹到這了,更多相關(guān)nestjs返回給前端數(shù)據(jù)格式內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!

原文鏈接:https://blog.csdn.net/kuangshp128/article/details/97240664

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 午夜五月天 | 四虎影视4hu最新地址在线884 | 三级aa久久| 精品国产自在天天线2019 | freesex性欧美炮机喷潮 | 男人天堂亚洲 | 亚洲欧洲综合 | 欧美日韩亚毛片免费观看 | 国产福利视频一区二区微拍 | 日韩一区视频在线 | 国产一级片视频 | 日本黄a三级三级三级 | 久久久久青草大香线综合精品 | 欧美一区二区三区在线观看免费 | 俄罗斯女同和女同xx | 菠萝视频在线完整版 | 午夜大片在线观看 | 女毛片| 女学生被老师调教在教室 | 四虎成人4hutv影院 | 国产欧美曰韩一区二区三区 | 亚洲第一综合网站 | 波多野结衣亚洲一区 | 高清国产精品久久久久 | 五月天色综合 | 三级网站午夜三级 | 亚洲香蕉综合在人在线视看 | 美女靠逼免费视频 | 纲手被鸣人插 | 国产成人a v在线影院 | 欧美一卡二卡科技有限公司 | 九九99九九精彩网站 | 丁香成人社| 亚洲男人天堂a | 亚洲欧洲日产v特级毛片 | 无码爽死成人777在线观看网站 | 国产精品1区2区 | 亚洲天堂男人网 | 动漫精品一区二区三区3d | 久久精品国产亚洲AV热无遮挡 | 国产精品高清一区二区三区不卡 |