公告:魔扣目录网为广大站长提供免费收录网站服务,提交前请做好本站友链:【 网站目录:https://www.morko.net 】, 免友链快审服务(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

通用课目体育训练成绩评定