日日操夜夜添-日日操影院-日日草夜夜操-日日干干-精品一区二区三区波多野结衣-精品一区二区三区高清免费不卡

公告:魔扣目錄網為廣大站長提供免費收錄網站服務,提交前請做好本站友鏈:【 網站目錄:http://www.ylptlb.cn 】, 免友鏈快審服務(50元/站),

點擊這里在線咨詢客服
新站提交
  • 網站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會員:747

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

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

一、返回的數據格式對比

1、直接返回的數據格式

{
    "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、我們自己包裝后的返回數據

{
    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"
    }
}

二、攔截全部的錯誤請求,統一返回格式

1、使用命令創建一個過濾器

nest g f filters/httpException

2、過濾器的代碼

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;
        // 設置返回的狀態碼、請求頭、發送錯誤信息
        response.status(status);
        response.header('Content-Type', 'application/json; charset=utf-8');
        response.send(errorResponse);
    }
}

3、在main.ts中全局注冊

.

..
import { HttpExceptionFilter } from './filters/http-exception.filter';

async function bootstrap() {
    ...
    // 全局注冊錯誤的過濾器
    app.useGlobalFilters(new HttpExceptionFilter());
}
bootstrap();

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

{
    "statusCode": 400,
    "error": "Bad Request",
    "data": {
        "message": [
            {
                "age": "必須的整數"
            }
        ]
    },
    "message": '請求失敗',
    "code": 1,
    "url": "/api/v1/cat"
}

三、統一請求成功的返回數據

1、創建一個攔截器src/interceptor/transform.interceptor.ts

2、攔截器的代碼

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、全局注冊

...
import { TransformInterceptor } from './interceptor/transform.interceptor';

async function bootstrap() {
    ...
    // 全局注冊攔截器
    app.useGlobalInterceptors(new TransformInterceptor());
    ...
}
bootstrap();

4、測試返回數據

{
    "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": "請求成功"
}


分享到:
標簽:nestjs 前端數據格式的封裝
用戶無頭像

網友整理

注冊時間:

網站:5 個   小程序:0 個  文章:12 篇

  • 51998

    網站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會員

趕快注冊賬號,推廣您的網站吧!
最新入駐小程序

數獨大挑戰2018-06-03

數獨一種數學游戲,玩家需要根據9

答題星2018-06-03

您可以通過答題星輕松地創建試卷

全階人生考試2018-06-03

各種考試題,題庫,初中,高中,大學四六

運動步數有氧達人2018-06-03

記錄運動步數,積累氧氣值。還可偷

每日養生app2018-06-03

每日養生,天天健康

體育訓練成績評定2018-06-03

通用課目體育訓練成績評定